Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to chain where query in rails 3 active record

I need to add conditions depending on params data.

@users = User.where('id', params[:id]) unless params[:id].nil?
@users = User.where('email', params[:email]) unless params[:email].nil?
@users = User.limit(10)

But it does not work for some reason. Thanks

like image 636
Tamik Soziev Avatar asked Apr 02 '12 02:04

Tamik Soziev


1 Answers

Each of your statements is replacing the @users variable, and as ActiveRecord evaluates each lazily, the first two are never being called.

If you want to maintain three separate queries and build things up that way you can do:

@users = User.limit(10)
@users = @users.where('id', params[:id]) if params[:id]
@users = @users.where('email', params[:email]) if params[:email]

It isn't the prettiest, but it will work. However, I recommend keeping it to a single method call and defining it in the model.

# In the model

def self.by_id_and_email(id, email)
  users = limit(10)
  users = users.where('id', id)       if id.present?
  users = users.where('email', email) if email.present?

  users
end

# In the controller / out of the model

User.by_id_and_email(params[:id], params[:email])

That way you can use the method again, refine it, and write speed(ier) tests against it.

like image 189
Parker Selbert Avatar answered Oct 10 '22 11:10

Parker Selbert