简体   繁体   中英

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 ?

You can use ActiveRecord::SpawnMethods#merge for that:

@query1.merge(@query2)
# SELECT "users".* FROM "users" WHERE "users"."survey_response" = "foo" AND "users"."profile" = "bar"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM