views:

1191

answers:

3

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.

+5  A: 

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"
)
Simone Carletti
I'm looking for "no-string" solution, as hash {...}.
xpepermint
It doesn't exist a solution using Hash.
Simone Carletti
+3  A: 

Use AR Extensions for this. It supports the following condition modifiers:

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

Read this article for more details.

KandadaBoggu
+2  A: 

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.

hash_conditions = {:category => 'computers'}
conditions = Product.merge_conditions(hash_conditions) + ' AND products.id NOT IN(1139) '
products = Product.find(:all, :conditions => conditions)