What difference between two approaches shown below and what is better:
user.photos & Photo.public
and
user.photos.where('photos.id IN (?)', Photo.public.select(:id))
Is there better way to combine two active record queries ?
The first will be using an array join, the second is doing two queries, neither is as efficient as adding another scope to your Photo model:
# Photo Model
scope :public, where {:public => true }
scope :user, lambda { |user| where("user_id = ?", user) }
# Controller
Photo.public.user(user)
Given that Photo#public is a scope, ex.:
scope :public, -> { where(:public => true) }
You can simply write
user.photos.public
如果您不能使用新范围,我建议您:
user.photos.merge(Photo.public)
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.