user6442102
user6442102

Reputation: 25

How do I stack queries using Active record?

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

Answers (2)

Rob
Rob

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

Sebasti&#225;n Palma
Sebasti&#225;n Palma

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

Related Questions