我无法弄清楚如何在我的视图中访问多级关联。
我有 3 个主要模型:类别、活动和投票(省略不相关的行(:
class Category < ApplicationRecord
belongs_to :user
# Many-to-many relationship with model Activity
has_and_belongs_to_many :activity, dependent: :destroy
# Link to votes
has_many :vote, through: :activity
end
class Activity < ApplicationRecord
belongs_to :user
# Many-to-many relationship with model Activity
has_and_belongs_to_many :category
# An Activity can have multiple votes
has_many :vote, dependent: :destroy
end
class Vote < ApplicationRecord
# Many (users and activities) to one (votes) relationship
belongs_to :user
belongs_to :activity
end
我在"类别"和"活动"之间有一个用于多对多关系的连接表。
我想完成的是,在"类别"视图中,显示该类别中的活动数以及该类别中的投票数(通过"活动投票"(。第一个工作正常:
<% @categories.each do |category| %>
<%= category.activity.ids.count %>
<% end %>
后者显示票数,没有(undefined method "vote"
( - 与上面在同一块中:
<%= category.activity.vote.ids.count %>
以下 2 行中没有一行我的类别控制器用于此目的:
def index
# With this I can already access the associated Activities, but not the Votes
@categories = Category.all()
end
def index
# Changing the Category controller as follows seems to have no effect on being able to access the number of votes
@categories = Category.joins({:activity => :vote}).group('category_id').order('COUNT(activities.id) DESC')
end
我这里一定错过了什么?
编辑:根据尼尔的建议,这就是我现在的观点:
<% @categories.each do |category| %>
<% category.activity.each do |activity| %>
<%= activity.vote.ids.count %>
<% end %>
<% end %>
我可以看到你的日志吗?
我想你在这里有很多活动
'<%= category.activity.vote.ids.count %>'
尝试从下面的代码中查找投票。
'<%= category.activity.first.vote.ids.count %>'