开发者

Active Record "where" query from parent resource

开发者 https://www.devze.com 2023-02-18 16:18 出处:网络
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 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()")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号