Reputation: 37
Relatively new to rails, and am just trying to sort through my model relationships in order to find the number of users who have Favorited a particular post. Here are my models:
User.rb
has_many :favorites
has_many :favorite_posts, through: :favorites, source: :favorited, source_type: 'Post'
Post.rb
belongs_to :user
has_many :favorites
Favorite.rb
belongs_to :favorited, polymorphic: true
belongs_to :user
In my Posts#show view I want to call something like
<%= @post.favorited.count %>
and get the number of users who have favorited this post, but it tells me that this is an undefined method.
Any suggestions? thank you,
Upvotes: 1
Views: 342
Reputation: 102046
class User
has_many :favorites
has_many :favorite_posts, through: :favorites,
source: :favorited,
source_type: 'Post'
end
class Post
has_many :favorites, as: :favorited
end
class Favorite
belongs_to :user
belongs_to :favorited, polymorphic: true
end
This will let get a count through @post.favorites.size
- but you should either use a join or counter caches to avoid N+1 query issues.
class Favorite
belongs_to :user
belongs_to :favorited, polymorphic: true, counter_cache: true
end
Upvotes: 0
Reputation: 435
@engineersmnky is right, you will need to include the relationship on Post as well.
Additionally while you can get this information via a join, it won't let you efficiently query the top favorited posts or include the number of favorites in a table of posts. You should persist the count each time a favorite is added or removed, either using callbacks or a counter cache.
Upvotes: 2