Reputation: 113
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?
Upvotes: 1
Views: 401
Reputation: 1585
Add has_many :liked_posts, :through => :likes, :class_name => 'Post'
to User
and then call User.find(params[:id]).liked_posts
.
Upvotes: 5