从Rails ActiveRecord中的结果中排除一些ID

时间:2010-04-05 20:28:49

标签: ruby-on-rails ruby activerecord

我对以下部分的查询文章有以下声明

Article.all(:joins => :sections, :conditions => { :sections =>{ :id => [3, 4, 6, 7, 8, 9] }, :id_not_in => @some_ids  }, :limit => 4)

变量@some_ids是包含必须从结果中排除的文章ID的数组。

2 个答案:

答案 0 :(得分:9)

如果Article has_many :sections,请尝试:

Article.find(:all, :joins => :sections, :conditions => ["sections.id IN (?) AND
   id NOT IN (?)", [1,2,3], @some_ids], :limit => 4)

答案 1 :(得分:2)

Article.all(:joins => :sections, 
  :conditions => [ 'sections.id in ? and sections.id not in ?', 
  [3, 4, 6, 7, 8, 9], @some_ids ], :limit => 4)

未测试