【问题标题】:Comment attribute won't save in Rails?评论属性不会保存在 Rails 中?
【发布时间】:2014-02-22 15:56:20
【问题描述】:

我正在尝试保存评论的评论文本部分,但由于某种原因无法保存。 我正在检查我的服务器输出,并设置了注释属性,但实际保存时,结果显示为 NIL。

原来有 "comment"=>{"comment"=>"hello dude"}, "commit"=>"Sbmit Comment"

但是在保存中它保存了 NIL。

这是我的 cmets 表格

<div class="container">
    <% if user_signed_in? %>
<%= form_for([@answer, @comment]) do |f| %>

    <p>
        <%= f.label :comment %>
        <%= f.text_area :comment, :cols => "50", :rows => "30"%>
    </p>
    <p>
        <%= f.submit "Submit Comment" %>
    </p>
<% end %>
<% else %>
<p> <em>You must be signed in to comment</em> </p>
<% end %>
</div>

这是我的 cmets 控制器

class CommentsController < ApplicationController
    def create
        @answer = Answer.find(params[:answer_id])
        @comment = @answer.comments.new(params[:comments])
        @comment.writer = current_user.username
        @comment.save
            redirect_to question_path(@answer)
    end
end

这是我的模型。

class Comment < ActiveRecord::Base
  belongs_to :answer
  attr_accessible :anonymous, :comment, :writer, :votes
end

这是我的答案模型

class Answer < ActiveRecord::Base
    has_many :comments, dependent: :destroy
    belongs_to :question
    attr_accessible :anonymous, :answer, :commenter, :votes, :comments_attributes
end

有什么想法吗?

编辑:我使用了 params[:comment],但是,它说我不能批量分配属性来回答,即使 answer 具有 attr_accessible: :cmets_attributes

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    在这一行中 @comment = @answer.comments.new(params[:comments]):comments 更改为 :comment

    【讨论】:

    • 如果我使用 :comment,它说不能批量分配属性来回答,但我的回答里面有 attr_accessible: cmets_attributes,路由里面有 'cmets'。
    • 在您的答案模型中添加:accepts_nested_attributes_for :comments
    • 这在 5 分钟前肯定不起作用,但现在它起作用了!嗯,不知道为什么,但谢谢!
    【解决方案2】:

    您尝试在控制器中使用 params[:cmets] 进行保存,但传递的内容会响应 params[:comment]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2011-01-05
      相关资源
      最近更新 更多