我有以下作用域,我知道它不是最优解:
scope :event_stream_for, lambda{ |user|
where("target_id in (?) and target_type = ?", user.events.collect(&:id), "Event")
}
这将创建3个查询。我该如何进行优化?
或者,我如何将整个SQL语句放在作用域的lambda中,例如:
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))
谢谢