Ruby on rails 同时属于多个其他模型的模型

Ruby on rails 同时属于多个其他模型的模型,ruby-on-rails,ruby,activerecord,associations,Ruby On Rails,Ruby,Activerecord,Associations,与下列协会: class User < ActiveRecord::Base has_many :posts has_many :comments end class Post < ActiveRecord::Base belongs_to :user has_many :comments end class Comment < ActiveRecord::Base belongs_to :user belongs_to :post end 但是要

与下列协会:

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
end

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

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end
但是要访问关联的
Post
我需要手动设置它的父项:

@comment.post = Post.find params[:post_id]

在创建新的
注释时,是否有更好的方法来执行此操作

如果希望comments对象与或关联,则多态关联将起作用

class注释

您将无法使用@comment.post,但可以使用@comment.commentable作为您的帖子或用户对象,具体取决于与该实例关联的对象

我会使用嵌套资源

resources :posts do
  resources :comments
end
然后,我将通过post构建评论,并将其合并到当前用户的id中,这样您就不需要隐藏字段,这些字段显然可以被操纵

class CommentsController
  def new
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new
  end

  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(comment_params)
  end

  private

  def comment_params
    params.require(:comment).permit(:content).merge({ user_id: current_user.id })
  end

end
您只需要在创建注释时合并当前用户,这样您就可以拥有一个私有的comment\u creation\u params方法,该方法在创建时被调用

def comment_params
  params.require(:comment).permit(:content)
end

def comment_creation_params
  comment_params.merge({ user_id: current_user.id })
end

所以,主要的想法就是去掉
Post.find(params[:Post\u id])

如果我是你,我会在
comment\u params
中明确插入
post\u id

def comment_params
  params.require(:comment).permit(:text).merge(post_id: params[:post_id])
end
为了确保帖子存在,我将在评论中添加验证:

class Comment
  validates :post, presence: true
  #...
end
如果您不想将评论与帖子关联,您可以跳过此验证或编写自定义验证

validate do
  errors.add(:post_id, 'There is no post') unless Post.find(post_id).present?
end


其中一个答案建议使用嵌套资源解决方案,这是另一个解决方法。

您的资源是否嵌套?看起来它们是。不,它们还没有。你能为用户的帖子和评论提供你的模式吗?
属于
方法只有在此类包含外键时才应使用。你的
评论
模型中有
用户id
发布id
吗?@AzatGataoulline是的,我有。在我的代码中,
发布
用户
都与
评论
相关联。他希望它都属于这两个,按照我的理解,有多个
属于
,而不是一个。@ABrowne,这不是关于用户的评论。这是用户对帖子的评论。这两个字段都是必需的。当我第一次读这篇文章时,我的假设是错误的。我假设这是一条针对用户或帖子的评论,而不是OP的意思,正如你所说,这看起来像是用户对帖子的评论。我认为更重要的是在帖子的显示页面上显示评论,以及谁发布了评论。什么创建回调?你的意思是创造行动吗?这是我在底部说的。在创建操作中,您将使用
@comment=@post.comments.new(comment\u creation\u params)
这只解决了这个特殊情况,但增加了另一个问题:我不能做
@comment.user
来访问用户,通常我不能从
所属的:user
@Sajjad添加的功能中获益,只需添加
属于\u to:user
,然后您就可以执行
@comment.user
很抱歉,在rails控制台中,当我尝试
@comment.post
时,我得到了相关的帖子。但在控制器中,我得到零。注释参数也包含
:body
:comment\u id
,但在
@comment之前或之后我仍然得到零。save
@Sajjad,这对我来说似乎是一个单独的问题。你能用你的控制器代码发布一个单独的问题吗?我的代码的问题是,我不能使用@comment.post访问关联的帖子,不能将
评论
post
@Sajjad关联,当一条评论事实上属于post时,你为什么不想让评论与post关联?@Sajjad,我已经编辑了我的答案。根本不需要添加验证,
comment\u params
起到了作用。如果我把我的意思表达得如此糟糕,我感到很抱歉。我的意思是,将
Comment
的实例与
Post
class Comment
  validates :post, presence: true
  #...
end
validate do
  errors.add(:post_id, 'There is no post') unless Post.find(post_id).present?
end