I have the following scope, which I know is not optimal:
scope :event_stream_for, lambda{ |user|
where("target_id in (?) and target_type = ?", user.events.collect(&:id), "Event")
}
This creates 3 queries. How can I optimize it?
Alternatively, how do I put the whole sql statement in lambda of the scope, like
SELECT * FROM activities WHERE target_type =='Event' AND target_id IN (SELECT DISTINCT id FROM events WHERE (host_id == user.id OR invitee_id == user.id))
Thank you
Assuming user has many events and each event belongs to a user.
this will run one query. Haven’t tested my code with your table, but it should work similarly.
———————– based on your edited question ——————-
SELECT * FROM activities WHERE target_type ==’Event’ AND target_id IN (SELECT DISTINCT id FROM events WHERE (host_id == user.id OR invitee_id == user.id))
It’s all about ActiveRecord Relation, http://railscasts.com/episodes/239-activerecord-relation-walkthrough?view=asciicast
Try this on console, and if it works you can just simply change it to scope.
Since i m not sure what you are trying to do, you may need some adjustment.