Question

I have the following associations in my application:

# user.rb
has_many :posts, :dependent => :destroy
has_many :likes, :dependent => :destroy

# post.rb
belongs_to :user
has_many :likes, :dependent => :destroy


# like.rb
belongs_to :user
belongs_to :post

When I'm trying to access all the posts that a user liked I'm using the following loop

@user = User.find(params[:id])
@posts_user_likes = []
@user.likes.each do |like| # TODO optimize
  @posts_user_likes << Post.find_by_id(like.post_id)
end

but that seems very inefficient.

What's the best way to improve my code, either with different association or different way of looping?

Was it helpful?

Solution

Add has_many :liked_posts, :through => :likes, :class_name => 'Post' to User and then call User.find(params[:id]).liked_posts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top