Reputation: 25
I want to stack or join multiple queries to the same model.
For instance, I have these two queries:
@query1 = User.where(:survey_response => params[:survey_response])
@query2 = User.where(:profile => params[:profile])
How can I execute @query1.@query2
?
Upvotes: 1
Views: 45
Reputation: 21
Personally I would create a new method in the User model. For example:
class User < ActiveRecord::Base
def survey_response
where(:survey_response => params[:survey_response])
end
def profile
where(:profile => params[:profile])
end
end
You can also chain them in a method:
def profile_and_user_reponse
where(:profile => params[:profile])
.where(:survey_response => params[:survey_response])
end
Or just call <User>.survey_response.profile
Upvotes: 0
Reputation: 33420
You can use ActiveRecord::SpawnMethods#merge
for that:
@query1.merge(@query2)
# SELECT "users".* FROM "users" WHERE "users"."survey_response" = "foo" AND "users"."profile" = "bar"
Upvotes: 1