Rails where.not 跳过一些记录
Rails where.not skips some records
我尝试获取除类别 [20,21,22] 以外的所有视频
这是我的查询
@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">]>
我做错了什么?
试试这个:
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]})
您查询错误。
尝试:
Video.where.not(id: Video.joins(:categories).where(categories: { id: [20,21,22]}).pluck(:id))
我尝试获取除类别 [20,21,22] 以外的所有视频
这是我的查询
@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">]>
我做错了什么?
试试这个:
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]})
您查询错误。 尝试:
Video.where.not(id: Video.joins(:categories).where(categories: { id: [20,21,22]}).pluck(:id))