Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord conditions

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.

like image 994
xpepermint Avatar asked Feb 25 '10 12:02

xpepermint


People also ask

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

Can you use ActiveRecord without Rails?

One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What is eager loading Rails?

Eager loading solves this problem by creating a left outer join on the table, returning all of the data in a single query. Adding an eager load is as simple as adding an :includes statement to the controller.

What is an ActiveRecord relation?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).


2 Answers

Rails 3

Use squeel gem.

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

Rails 2

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']}
)
like image 107
Harish Shetty Avatar answered Oct 04 '22 21:10

Harish Shetty


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"
)
like image 45
Simone Carletti Avatar answered Oct 04 '22 19:10

Simone Carletti