0

我已经关注了 Railscast第 262 集关于祖先的教程。但是当我提交表单时,rails 服务器日志显示parent_id为空:

rails server日志:

Started POST "/posts/1/comments" for 127.0.0.1 at 2013-09-26 16:14:59 +0200
Processing by CommentsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"9+9U/etsazbrJxwWah/eRD9v3fKBnjpy+y5s+g7N/Bw=", "comment"=>{"parent_id"=>"", "author"=>"some name", "author_email"=>"mail@domain.com", "author_url"=>"", "content"=>"banane"}, "commit"=>"Post Comment", "post_id"=>"1"}
  Post Load (0.1ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", "1"]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "comments" ("author", "author_email", "author_url", "content", "created_at", "post_id", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["author", "some name"], ["author_email", "mail@domain.com"], ["author_url", ""], ["content", "banane"], ["created_at", Thu, 26 Sep 2013 14:14:59 UTC +00:00], ["post_id", 1], ["updated_at", Thu, 26 Sep 2013 14:14:59 UTC +00:00]]
   (38.6ms)  commit transaction
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://0.0.0.0:3000/posts/1
Completed 302 Found in 49ms (ActiveRecord: 39.4ms)

comments_controller.rb

def new
  @comment = Comment.new
  @comment.parent_id=params[:parent_id]
end

def create
  @post = Post.find(params[:post_id])    
  @comment = @post.comments.create(params[:comment].permit(:author, :author_email, :author_url, :content, :parent_id))

  respond_to do |format|
    if @comment.save
      stuff
    else
      other stuff
    end
  end
end

def comment_params
  params.require(:comment).permit(...some stuff..., :parent_id)
end

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :post
  has_ancestry
end

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments, :dependent => :destroy
  accepts_nested_attributes_for :comments
end

views/posts/show.html.erb

<% @post.comments.each do |comment| %>
  <%= show some stuff %>
  <%= link_to (post_path(:anchor => "respond", :parent_id => comment)) do%>
    <%= "Reply"%>
  <% end %>
<% end %>
<%= render 'comments/comment_form'%>  

_comment_form.html.erb

<%= form_for [@post, @post.comments.build], html: { :id => "commentform"} do |f| %>
<%= f.hidden_field :parent_id %>
<%= some fields %>
<%= f.submit "Post Comment"%>

Rails 调试信息:

--- !ruby/hash:ActionController::Parameters
parent_id: '17'
action: show
controller: posts
id: '1'

我猜我的 create 方法有问题CommentsController,但我无法弄清楚缺少什么。所以,我得到了这个工作。我正在从我的帖子/显示视图提交表单,因此我还必须调用@comment = Comment.new(:parent_id => params[:parent_id])后控制器的显示操作。

4

2 回答 2

1

添加:parent_idcomment_params评论控制器中。

于 2014-06-09T20:25:56.247 回答
1

如果您使用的是 Rails >3.0.0,请在您的评论控制器中尝试此操作:

@comment = Comment.new
@comment.parent_id=params[:parent_id]

代替

@comment = Comment.new(:parent_id => params[:parent_id])
于 2013-11-28T15:23:02.130 回答