I need to create a Query that evaluates if the parent object has receives at least two likes. If he has, then include it in the random query.
I tried something like this but it didn't work.
@attachments = Attachment.joins('LEFT OUTER JOIN users ON users.id = attachments.user_id').开发者_开发问答where("received_likes_count > ?",2).order("random()")
Does this work for you? I'm envisioning your User is the parent, and the attachments table has a user_id, but I'm not entirely sure based on your wording of the question.
The main trick of this is it uses a sub-select to gather ids for use in the IN clause.
@attachments = Attachment.where(
'user_id IN (
SELECT id FROM users WHERE received_likes_count > ?
)', 2
).order('random()')
MySQL?
@attachments = Attachment.joins(:users).where("received_likes_count > ?",2).order("rand()")
精彩评论