0

我有三个看起来像这样的模型:

Class User < ActiveRecord::Base
  has_many :comments
end

Class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :votes
end

Class Vote < ActiveRecord::Base
  belongs_to :comment
end

现在我想获得与用户评论相关的所有投票,如下所示:

@user.comments.votes

但这会引发错误:

undefined method `votes' for #<ActiveRecord::Relation:0x3f6f8a0>

这似乎应该可以工作,但我怀疑 ActiveRecord 正在对更深层次的 has_many 关系咳嗽。我已经将一个 SQL 查询组合在一起,可以获得所需的结果,但我怀疑使用纯 ActiveRecord 有一种更简洁的方法。有小费吗?

4

2 回答 2

3

您应该使用has_many :through 关联

在你的情况下,它会是

Class User < ActiveRecord::Base
  has_many :comments
  has_many :votes, :through => :comments
end

Class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :votes
end

Class Vote < ActiveRecord::Base
  belongs_to :comment
end

然后简单地获得选票

@user.votes
于 2013-01-11T19:44:03.177 回答
1

试试这个:

Vote.joins(comment: :user).where(users: {id: @user.id})
于 2013-01-11T19:27:45.100 回答