mardi 21 juillet 2015

Rails Activerecord query for joining multiple tables

AdminUser has_many User

User has_many Posts

Posts has_many Comments

I want to get a list of all comments under every post created by every User under this AdminUser.

To get all comments under every post done by 1 user is easy. I would use something like

        comments=Comment.joins(:post).where("posts.user_id= ?",userid.to_s )

But here I need to go one more level up. ie get comments from every post made by every user under 1 admin_user. I have never used more than one join before, so I am a bit confused.

If I could use Activerecord association inside strings it might look like

        comments=Comment.joins(:post).joins(:user).where("posts.user.admin_user.id=?",adminuser_id)

But I cannot use posts.user.admin_user

Aucun commentaire:

Enregistrer un commentaire