来自帖子#show view comments只有在第一条评论已经创建时才能添加,否则会抛出此路由错误:
No route matches {:action=>"show", :controller=>"posts", :view=>"comments"}
终端读取:
Started POST "/comments" for 127.0.0.1 at 2011-05-17 18:18:03 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BPeNvVJh+dLBhpiZK16phQHp7UV4MasPyQW6PL9VG8I=", "comment"=>{"post_id"=>"", "parent_id"=>"", "name"=>"", "content"=>"yo"}, "commit"=>"Reply"}
AREL (0.9ms) INSERT INTO "comments" ("name", "content", "post_id", "created_at", "updated_at", "ancestry") VALUES ('', 'yo', NULL, '2011-05-18 01:18:03.445466', '2011-05-18 01:18:03.445466', NULL)
Completed in 133ms
ActionController::RoutingError (No route matches {:action=>"show", :controller=>"posts", :view=>"comments"}):
app/controllers/comments_controller.rb:14:in `block (2 levels) in create'
app/controllers/comments_controller.rb:9:in `create'
如果已创建帖子的第一条评论
帖子#显示:
<%= render @post %>
<%= nested_comments @comments.arrange(:order => :created_at) %>
<%= render "comments/form" %>
形式:
<%= simple_form_for :comment, :url => { :controller => :comments, :action => "create" } do |f| %>
<%= f.input :post_id, :required => false, :as => :hidden %>
<%= f.input :parent_id, :required => false, :as => :hidden %>
<%= f.input :name, :label => false, :placeholder => "Name (optional)", :required => false %>
<%= f.input :content, :label => false, :placeholder => "Reply", :as => :text %>
<%= f.button :submit, "Reply" %>
<% end %>
评论控制器:
def new
@comment = Comment.new(:parent_id => params[:parent_id], :post_id => params[:post_id])
end
def create
@comment = Comment.create(params[:comment])
@comment.save
respond_to do |format|
format.html do
if @comment.errors.present?
render :new
else
redirect_to(post_path(@comment.post, :view => "comments"))
end
end
format.js
end
end
路线:
root :to => "posts#index"
resources :topics
resources :posts
resources :comments
模式:
create_table "comments", :force => true do |t|
t.string "name"
t.text "content"
t.integer "post_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "ancestry"
end
add_index "comments", ["ancestry"], :name => "index_comments_on_ancestry"
create_table "posts", :force => true do |t|
t.string "name"
t.string "title"
t.text "content"
t.integer "topic_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "topics", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
答案 0 :(得分:1)
我没有对此进行过测试,但尝试更换
redirect_to(post_path(@comment.post, :view => "comments"))
在控制器的创建操作中:
redirect_to(post_path(:id => @comment.post_id, :view => "comments"))
如果上述方法不起作用,我们会尝试其他方法。无论如何,这似乎是你问题的所在。
答案 1 :(得分:0)
看起来您的表单与实际评论无关,因为它只是传递了一个符号。试试这是你的观点
<%= simple_form_for @comment, :url => { :controller => :comments, :action => "create" } do |f| %>
...
实际上,这应该允许你抛弃:url
参数
<%= simple_form_for @comment do |f| %>
然后确保在控制器中定义@comment
并设置post_id
@comment = Comment.new
@comment.post_id = @post.id