Is there a way to conditionally append query methods to a ActiveRecord::Relation?
For instance, I'm searching for Users, but I only was the last_name included in the search under certain conditions. Can you append queries to an ActiveRecord::Relation object?
i_want_to_search_for_last_names = true pending_relation = User.where(:first_name => "John") pending_relation << where(:last_name => "Doe") if i_want_to_search_for_last_names @users = pending_relation.all
preguntado el 08 de noviembre de 11 a las 17:11
You code is almost right, except some things. Here what you can do (don't forget: you deals with ActiveRelation):
i_want_to_search_for_last_names = true @users = User.where(:first_name => "John") @users = @users.where(:last_name => "Doe") if i_want_to_search_for_last_names
As for me - I used this technique in my projects. Hope it helps you.