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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With