示例:
class Category
end
class Article
belongs_to :category
end
class Comment
belongs_to :article
end
class Votes
belongs_to :comment
end
我如何通过关联访问某类别的投票?
与: Category.first.votes
答案 0 :(得分:0)
首先,您需要完成关联:每个belongs_to
都应该有相应的has_many
/ has_one
class Category
has_many :articles
end
class Article
has_many :comments
belongs_to :category
end
class Comment
has_many :votes, class_name: :votes #rails will look for class Vote, so you have to specify that the class name is actually 'votes'
belongs_to :article
end
然后使用适当的,has_many通过关联
class Category
has_many :articles
has_many :comments, through: :articles
has_many :votes, through: :comments
end
现在你应该可以致电Category.first.votes
并获得第一类