9

有没有办法创造这样的条件?

@products = Product.find(:all,
  :limit => 5,
  :conditions => { :products => { :locale => 'en', :id NOT '1' }, :tags => { :name => ['a','b']})

我想列出不包括产品 1 的所有产品。谢谢。

4

4 回答 4

20

导轨 3

使用squeel宝石。

Product.where(
  :products => { :locale => 'en', :id.not_in => '1' }, 
  :tags => { :name => ['a','b']}
).limit(5)

导轨 2

为此使用AR 扩展。它支持以下条件修饰符:

* _lt => less than
* _gt => greater than
* _lte => less than or equal to
* _gte => greater than or equal to
* _ne => not equal to
* _not => not equal to

现在您可以按如下方式重写您的查询:

@products = Product.find(:all,
  :limit => 5,
  :joins => [:tags],
  :conditions => { :locale => 'en', :id_not => '1', :tags => { :name => ['a','b']}
)
于 2010-02-25T18:23:07.230 回答
9

它应该是这样的。原始查询不是很清楚,请根据您的需要进行调整。

@products = Product.find(:all,
  :limit => 5,
  :conditions => ["locale = ? AND id <> ? AND tags.name IN (?)", "en", 1, ['a','b'],
  :joins => "tags"
)
于 2010-02-25T13:45:45.117 回答
9

另一种方法是使用将哈希条件转换为字符串的 merge_conditions。然后您可以添加任何您想要的内容或使用其他选项再次调用 merge_conditions。

hash_conditions = {:category => 'computers'}
conditions = Product.merge_conditions(hash_conditions) + ' AND products.id NOT IN(1139) '
products = Product.find(:all, :conditions => conditions)
于 2010-05-12T22:40:29.933 回答
2

导轨 3.2.9


控制器

  @products = Product.english_but_not(1).with_tags('a','b').limit(5)

模型

class Product < ActiveRecord::Base
  attr_accessible :locale
  has_many :tags
  scope :english, -> { where(:locale => 'en') }
  scope :except_id, ->(id) { where(arel_table[:id].not_eq(id)) }
  scope :english_but_not, ->(id) { english.except_id(id) }
  scope :with_tags, ->(*names) { includes(:tags).where(:tags => {:name => names}) }
end
于 2012-12-07T09:50:52.757 回答