Rails ActiveRecord条件

时间:2010-02-25 12:38:11

标签: ruby-on-rails conditional-statements rails-activerecord

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

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

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

4 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:9)

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

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

答案 2 :(得分: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)

答案 3 :(得分:2)

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