xpe*_*int 9 ruby-on-rails conditional-statements rails-activerecord
有没有办法创造这样的条件?
@products = Product.find(:all,
:limit => 5,
:conditions => { :products => { :locale => 'en', :id NOT '1' }, :tags => { :name => ['a','b']})
Run Code Online (Sandbox Code Playgroud)
我想列出所有产品,不包括产品1. Thx.
Har*_*tty 20
Rails 3
使用squeel gem.
Product.where(
:products => { :locale => 'en', :id.not_in => '1' },
:tags => { :name => ['a','b']}
).limit(5)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
现在,您可以按如下方式重写查询:
@products = Product.find(:all,
:limit => 5,
:joins => [:tags],
:conditions => { :locale => 'en', :id_not => '1', :tags => { :name => ['a','b']}
)
Run Code Online (Sandbox Code Playgroud)
它应该是这样的.原始查询不是很清楚,根据您的需要进行调整.
@products = Product.find(:all,
:limit => 5,
:conditions => ["locale = ? AND id <> ? AND tags.name IN (?)", "en", 1, ['a','b'],
:joins => "tags"
)
Run Code Online (Sandbox Code Playgroud)
小智 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29447 次 |
| 最近记录: |