Rails where.not跳过一些记录

时间:2015-10-18 16:30:30

标签: ruby-on-rails ruby-on-rails-4 join activerecord associations

我尝试获取除了类别[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">]>

我做错了什么?

3 个答案:

答案 0 :(得分:1)

试试这个:

array = [21,22,23]
@cc = Video.joins(:categories).where("category.id not in (?)", array)

修改

想想我发现了问题。假设您的Video模型与has_many处于Category关系。所以你应该这样做:

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])

答案 1 :(得分:1)

试试这个,

@cc = Video.includes(:categories).references(:categories).where.not(categories: { id: [20,21,22]})

参考, https://robots.thoughtbot.com/activerecords-wherenot

答案 2 :(得分:0)

您正在进行错误的查询。 试试:

Video.where.not(id: Video.joins(:categories).where(categories: { id: [20,21,22]}).pluck(:id))