【发布时间】:2017-01-03 21:29:24
【问题描述】:
对 Rails 比较陌生,我只是想整理一下我的模型关系,以便找到收藏特定帖子的用户数量。这是我的模型:
用户.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
在我的 Posts#show 视图中,我想调用类似的东西
<%= @post.favorited.count %>
并获取收藏此帖子的用户数量,但它告诉我这是一个未定义的方法。
有什么建议吗?谢谢,
【问题讨论】:
-
那是因为
favorited不是Post方法。试试@post.favorites.count虽然我相信Post模型也需要has_many :favorites, as: :favorited
标签: ruby-on-rails ruby activerecord model