1

在我的评论控制器中,我有以下内容

类 CommentsController < ApplicationController

  def create
    @comment_hash = params[:comment]
    #@comment = comment.new(comment_params)
    @obj = @comment_hash[:commentable_type].constantize.find(@comment_hash[:commentable_id])    
    @comment = Comment.build_from(@obj, current_user.id, @comment_hash[:body])
    binding.pry
    #...

在那个地方binding.pry

@comments_hash 是

{"body=>"asdf comment body",
 "commentable_type"=>"Hack",
 "commentable_id"=>"2"}

@obj 是

#<Hack id: 2, created_at: "2014-09-16 00:00:00",
updated_at: "2014-09-16 00:00:00", 
body: "some text", 
user_id: 1, 
comment_threads_count: 0>

但是@comment 输出

#<Comment id: nil, 
commentable_id: 2, 
commentable_type: "Hack", 
title: nil, body: "asdf, 
comment body", 
subject: nil, 
user_id: 1, 
parent_id: nil, 
lfg: nil, rgt: 
nil, created_at: nil, 
updated_at: nil>

为什么这里有这么多东西是零?当代码正常工作时,我对该方法的所有参数build_from都与以前相同。

尝试调用时的终端输出@comment.save

undefined method 'user' for #<Comment:0x5d1b1b0>

我不确定这意味着什么。我有一个 user_id 关联。我的参数哈希中没有看到用户参数。

任何帮助将非常感激。

4

1 回答 1

0

@Substantial 您的怀疑是正确的。

即使我通过acts_as_commentable_with_threading 方法建立了关联,我仍然必须has_many belongs_to在用户和评论之间建立关联。一旦我添加了has_many belongs_to关系,事情就解决了。(当我再次删除它时,它停止工作)。

acts_as_commentable_with_threading用户模型中拥有是用于发布对用户的评论,而不是指定评论属于用户。因此,如果您想对用户发表评论,则需要该方法和评论模型中的has_many :comments&belongs_to :user

如果您只想对另一个模型进行评论,请将方法放入该模型中,然后放入has_many :comments用户模型和belongs_to :user评论模型中

于 2014-09-17T17:14:37.267 回答