Rails的where.not跳过一些记录
我尝试获取除了那些所有视频与类别[20,21,22]Rails的where.not跳过一些记录
这是我的查询
@cc = Video.joins(:categories).where.not(categories: { id: [20,21,22]})
但是当我做@cc.find(113).categories
我得到这个
#<ActiveRecord::Associations::CollectionProxy
[#<Category id: 21, title: "music">, #<Category id: 22, title: "movies">,
#<Category id: 28, title: "collage">]>
我在做什么错?
你是做了错误的查询。 与尝试:
Video.where.not(id: Video.joins(:categories).where(categories: { id: [20,21,22]}).pluck(:id))
这个工程,但不是这个矫枉过正的查询? –
它会生成多少个查询?我猜只是一个。如果它生成两个查询,则用'select(:id)'替换'pluck(:id)'。 – coorasse
这样做的诀窍:)我的跳跃有一种更优雅的方式来写这个查询,但我想这真的没关系,当表现是好的:) –
试试这个:
array = [21,22,23]
@cc = Video.joins(:categories).where("category.id not in (?)", array)
编辑
想我发现了问题。假设您的Video
模型与Category
的关系为has_many
。所以,你应该做的:
class Video < ActiveRecord::Base
has_many :categories
has_many :excluded, -> (array) { where("id not in (?)", array) }, class_name: 'Category'
end
而且你怎么称呼它那样:
Video.find(113).excluded([21,22,23])
试试这个,
@cc = Video.includes(:categories).references(:categories).where.not(categories: { id: [20,21,22]})
仍然是一样的。我仍然可以在检索到的集合中找到具有这些错误类别的ID为113的视频 –
可以向我展示查询已解雇,还有@ cc.categories –
这是查询已解雇 SELECT“videos”。“id”AS t0_r0 ,“videos”。“id_string”AS t0_r1,“videos”。“title”AS t0_r2,“videos”。“duration”AS t0_r3,“videos”。“thumbnail”AS t0_r4,“videos”。“rating”AS t0_r5 ,“videos”。“created_at”AS t0_r6,“videos”。“updated_at”AS t0_r7,“categories”。“id”AS t1_r0,“categories”。“title”AS t1_r1 FROM“videos”LEFT OUTER JOIN“categories_videos” ON“categories_videos”。“video_id”=“videos”。“id”LEFT OUTER JOIN“categories”ON“categories”。“id”=“categories_videos”。“category_id”WHERE(“categories”。“id”NOT IN 20,21,22)) –
见我的编辑... – Brozorec