Ruby-on-rails Rails ActiveRecord 条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2333970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:19:55  来源:igfitidea点击:

Rails ActiveRecord conditions

ruby-on-railsconditional-statementsrails-activerecord

提问by xpepermint

Is there a way to create a condition like this?

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

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

I would like to list all products not including product 1. Thx.

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

回答by Harish Shetty

Rails 3

导轨 3

Use squeelgem.

使用squeelgem。

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

Rails 2

导轨 2

Use AR Extensionsfor this. It supports the following condition modifiers:

为此使用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

Now you can rewrite your query as follows:

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

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

回答by user339798

Another way is to use the merge_conditions which turns the hash conditions into a string. Then you can add on whatever you want or call merge_conditions again with other options.

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

回答by Simone Carletti

It should be something like this. The original query wasn't really clear, adapt it to your needs.

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

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

回答by Rafael Perea

Rails 3.2.9

导轨 3.2.9



Controller

控制器

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


Model

模型

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