除了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">]>我做错了什么?
发布于 2015-10-18 17:10:11
您正在执行错误的查询。试着:
Video.where.not(id: Video.joins(:categories).where(categories: { id: [20,21,22]}).pluck(:id))发布于 2015-10-18 16:35:22
试试这个:
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])发布于 2015-10-18 16:42:24
尝尝这个,
@cc = Video.includes(:categories).references(:categories).where.not(categories: { id: [20,21,22]})https://stackoverflow.com/questions/33200349
复制相似问题