我已经关注了Railscast episode #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'
我想在CommentsController
中我的创建方法有些不对劲,但我无法弄清楚缺少什么。所以,我得到了这个工作。我在帖子/节目视图中提交表单,所以我不得不在后控制器的show动作中调用@comment = Comment.new(:parent_id => params[:parent_id])
。
答案 0 :(得分:1)
如果您使用的是Rails&gt; 3.0.0,请在评论控制器中尝试:
@comment = Comment.new
@comment.parent_id=params[:parent_id]
而不是
@comment = Comment.new(:parent_id => params[:parent_id])
答案 1 :(得分:1)
在评论控制器中将:parent_id
添加到comment_params
。