代码之家  ›  专栏  ›  技术社区  ›  xpepermint

轨道激活记录条件

  •  9
  • xpepermint  · 技术社区  · 15 年前

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

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

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

    4 回复  |  直到 12 年前
        1
  •  20
  •   Harish Shetty    13 年前

    钢轨3

    使用 squeel 宝石。

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

    钢轨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']}
    )
    
        2
  •  9
  •   Simone Carletti    15 年前

    应该是这样的。最初的查询不太清楚,请根据您的需要进行调整。

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

    另一种方法是使用合并条件,将哈希条件转换为字符串。然后你可以添加你想要的任何东西,或者用其他选项再次调用合并条件。

    hash_conditions = {:category => 'computers'}
    conditions = Product.merge_conditions(hash_conditions) + ' AND products.id NOT IN(1139) '
    products = Product.find(:all, :conditions => conditions)
    
        4
  •  2
  •   Rafael Perea    12 年前

    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