如何模拟多对多的关系

时间:2010-01-28 01:37:57

标签: ruby-on-rails

这是场景, 文章有很多评论 用户可以为许多文章撰写许多评论

评论表包含

user_id
article_id

作为外键

我的模型设置如此

class User < ActiveRecord::Base
  has_many :comments
  has_many :articles, :through => :comments

class Article < ActiveRecord::Base
  has_many :comments
  has_many :users, :through => :comments

class Comment < ActiveRecord::Base
  belongs_to :users
  belongs_to :articles

我的routes.rb具有以下代码

  map.resources :articles, :has_many => :comments  
  map.resources :users, :has_many => :comments

产生以下路线

new_article_comment
edit_article_comment
new_user_comment
edit_user_comment
etc...

这不是我想要的(至少不是我想要的),因为评论必须始终与用户和文章相关,我怎样才能获得这样的路线

new_user_article_comment
edit_user_article_comment

然后我就可以了

new_user_article_comment_path([@user, @article])

创建新评论

2 个答案:

答案 0 :(得分:0)

您可以使用嵌套路由执行此操作。本文就如何做到这一点有一个很好的例子:

http://weblog.jamisbuck.org/2007/2/5/nesting-resources

请注意,该文章基本上是说“不要这样做”:

  

“经验法则:资源永远不应该   嵌套超过1级深。一个   集合可能需要作用域   它的父母,但具体成员可以   总是被id直接访问,   并且不应该需要范围界定(除非   由于某种原因,id不是唯一的。“

但是,上述引用并不真正适用于您的操作,以及其他唯一ID尚未可用的情况,因为您还没有唯一的ID对于评论,用户和文章ID是绝对必要的。对同一页面的评论提供了这种资格:

  

Thijs van der Vossen说......   “我们发明了第二条经验法则;   资源只应嵌套   真正需要父ID的操作   (比如'index','new'和'create')。   我们开始使用它了   使用数据模型的应用程序   几乎完全分层,除了   它不是,它似乎工作   很友好地。为什么要保留父母   结构中url中的资源   是不是严格的等级?“

答案 1 :(得分:0)

您已创建循环数据库架构。不是真的推荐。

数据模型应如下所示:

class User < ActiveRecord::Base
  has_many :comments

class Article < ActiveRecord::Base
  has_many :comments

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :article

基本路由:

map.resources :articles do |articles|
  articles.resources :comments
end

然后决定还需要什么才能使其符合您的要求。