我正在试图找出如何为以下模型创建关联的最佳方式:
以下是我要满足的要求:
在路由方面,我希望能够为特定用户访问特定类别的帖子。例如:
http://domain.com/users/1/categories/1/posts
由于用户和类别之间没有直接关系,我不太确定如何最好地建立关联。我完全迷失了如何配置路线。
以下是我对模特的看法:
class User < ActiveRecord::Base
has_many :posts
end
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :metric
has_many :comments
end
class Comments < ActiveRecord::Base
belongs_to :post
end
这是我应该使用has_many:通过关系吗?或者像多态关联这样更复杂的东西?提前谢谢!
答案 0 :(得分:1)
是的,使用它是一个非常好的主意:
User has_many :comments, :through => :posts
如果您愿意,还可以通过以下方式获取类别评论:
Category has_many :comments, :through => :posts
请记住,通过关联只是一种工具,允许您直接执行user.comments之类的操作(并且通过关联来查找发布模型的用户注释)。