Rails ActiveRecord条件

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

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

我想列出所有产品,不包括产品1. Thx。

Rails 3

使用squeel gem。

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

Rails 2

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

 * _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']} ) 

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

 @products = Product.find(:all, :limit => 5, :conditions => ["locale = ? AND id <> ? AND tags.name IN (?)", "en", 1, ['a','b'], :joins => "tags" ) 

另一种方法是使用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) 

Rails 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