Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有多个父级的Ruby-on-rails模型_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

具有多个父级的Ruby-on-rails模型

具有多个父级的Ruby-on-rails模型,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,在我的Rails应用程序中,我有两个模型、文章和项目,它们都与用户相关。我想为每个模型添加注释。构建这个的最佳方式是什么 以下是我当前的设置: class Comment < ActiveRecord::Base belongs_to :article belongs_to :project end class Article < ActiveRecord::Base belongs_to :user has_many :comments end class Pr

在我的Rails应用程序中,我有两个模型、文章和项目,它们都与用户相关。我想为每个模型添加注释。构建这个的最佳方式是什么

以下是我当前的设置:

class Comment < ActiveRecord::Base
  belongs_to :article
  belongs_to :project
end

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Project < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class User < ActiveRecord::Base
  has_many :articles
  has_many :projects
  has_many :comments, :through => :articles
  has_many :comments, :through => :projects
end 
class注释:文章
有很多:评论,:到=>:项目
结束
这是处理结构的正确方法吗?如果是这样,我如何管理CommentsController,使其具有通过文章创建的文章id,以及通过项目创建的项目id?有没有特别的路线需要我安排


最后一条评论:评论并不一定要有用户。由于这是我的网站,我希望匿名观众能够留下评论。这是一项琐碎的任务吗

您可以使用结构相似但单独存储的
articlecoment
s和
ProjectComment
s,然后创建一个返回这两种类型注释的方法。

使
Comment
成为多态模型。然后创建一个多态关联


以下是Rails wiki的一个示例,以下是Ryan Bates的一个屏幕演员。

您可以查看-acts\u as\u可评论插件


或者你可以继续使用多态关系

这看起来几乎完美,但我如何处理注释的创建?让我困惑的是控制器代码,而这个例子并没有涉及到它。例如,假设我在一个项目页面上有一个表单,可以留下一条评论——在提交时,我如何将评论与该特定项目相关联?p=Project.find(…);p、 评论。创建(…)啊,好吧——我想我明白了。谢谢您可以对文章注释和项目注释使用单独的控制器。找到与注释关联的实体,并通过实体的#注释关联在控制器中创建它@project=project.find(params[:project_id])@project.comments.create!(params[:comment])邓肯:那么这会进入ProjectsController,在一个新动作中吗?