TheSuper
TheSuper

Reputation: 645

Get all relations to members in a relation

Let's say I have three models (models changed, I wouldn't use a has_many :through for this kind of relationship normally):

class User << ActiveRecord::Base
    has_many :image_users
    has_many :images, through: :image_users
end
class ImageUser << ActiveRecord::Base
    belongs_to :user
    belongs_to :image
end

class Image << ActiveRecord::Base
    has_many :image_users
    has_many :users, through: :image_users
    has_many :comments, through: :image_comments
end

class ImageComment << ActiveRecord::Base
    belongs_to :image
    belongs_to :comment
end


class Comment << ActiveRecord::Base
    has_many :image_comments
    has_many :images, through: :image_comments
end

Given a user, how do I select all comments on their images? Ideally I'd do this with ActiveRecord or SQL to avoid loading lots of objects into memory. Hopefully this hasn't been asked before, it was pretty difficult to google for.

Upvotes: 0

Views: 4244

Answers (3)

evanbikes
evanbikes

Reputation: 4171

You should be able to do this and let Rails handle the SQL:

@user.images.includes(:comments).map(&:comments)

Upvotes: 2

evanbikes
evanbikes

Reputation: 4171

If you take the relationships from @railsr's answer, you can do it like this:

Comment.where(image_id: @user.images.pluck(:id))

Granted, this takes two queries, but you could use some raw SQL and make it into one.

Upvotes: 1

kirqe
kirqe

Reputation: 2470

User
has_many :images
has_many :comments

Image
belongs_to :user
has_many :comments

Comment
belongs_to :user
belongs_to :image

and it's gonna be something like this

@user.images.each {|e| e.comments}

Upvotes: 1

Related Questions