ruby on rails - How to go from a relation to a relation of associated model in Active Record -
ruby on rails - How to go from a relation to a relation of associated model in Active Record -
i have had sort of situation
class post has_many :comments end
now if have relation of posts, how relation of comments on posts.
what looking
post.where(user: user).comments
but wont work. missing obvious here? seems mutual utilize case.
basically when post.where(user: user).includes(:comments)
preloading requisite comments already, want access them directly, without post.where(user: user).includes(:comments).map{|p| p.comments}.flatten.uniq
or that..
i'd define scope
scope :comments_in_user_posts, -> (user) { where(user: user).includes(:comments).map{|p| p.comments}.flatten }
then utilize post.comments_in_user_posts(user)
.
edit:
another alternative utilize comment.where(post: post.where(user: user))
ruby-on-rails ruby rails-activerecord
Comments
Post a Comment