9

このような条件を作成する方法はありますか?

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

商品1を除くすべての商品を出品したいのですが。Thx.

4

4 に答える 4

20

レール3

スクイールジェムを使用。

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

もう 1 つの方法は、ハッシュ条件を文字列に変換する 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 に答える