【问题标题】:acts_as_commentable_with_threading - "build_from" method failing?act_as_commentable_with_threading - “build_from”方法失败?
【发布时间】:2014-09-17 01:15:58
【问题描述】:

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

类 CommentsController

  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所在的位置,

@cmets_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 关联。我在参数哈希中没有看到用户参数。

任何帮助将不胜感激。

【问题讨论】:

  • 发布您的Comment 模型。

标签: ruby-on-rails acts-as-commentable


【解决方案1】:

@Substantial 你的怀疑是正确的。

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

在用户模型中具有acts_as_commentable_with_threading 是为了在用户上发布cmets,而不是指定评论属于用户。因此,如果您想在用户上发布 cmets,则需要该方法以及评论模型中的 has_many :commentsbelongs_to :user

如果您只想在另一个模型上使用 cmets,请将方法放入该模型中,并将 has_many :comments 放入用户模型中,并将 belongs_to :user 放入评论模型中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2016-01-03
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2023-04-07
    相关资源
    最近更新 更多