[英]Couldn't find Post without an ID in rails
In show.html.erb 在show.html.erb中
<%= form_for :comment, :url=> {:controller => 'comments', :action => 'create'} do |f| %>
<%= f.text_field :title %>
<%= f.text_area :comment %>
<%= f.hidden_field :id , :value => @post.id %>
<%= f.submit %>
<% end %>
in Comments_controller 在Comments_controller中
class CommentsController < ApplicationController
def create
@post = Post.find(params[:id])
@comments = @post.comments.create(params[:comment])
if @comments.save
redirect_to @post
else
redirect_to post_path
end
end
In Routes.rb resources :posts 在Routes.rb中的资源:posts
match '/create', :to => 'comments#create' , :as => :create
when i add any comment from view form it gives following error : 当我从视图表单添加任何评论时,出现以下错误:
'Couldn't find Post without an ID'
i cant figure out why params[:id] not returning Post ID ? 我不知道为什么params [:id]不返回Post ID? Note : I am using acts_as_commentable 注意:我使用的是acts_as_commentable
Got the answer 得到了答案
comments_controller should be as comments_controller应该是
class CommentsController < ApplicationController
def create
@post = Post.find(params[:comment][:id])
@comments = @post.comments.create(params[:comment])
if @comments.save
redirect_to @post
else
redirect_to post_path
end
end
end
@post = Post.find(params[:comment][:id]) @post = Post.find(params [:comment] [:id])
The reason your params[:id] not returning Post ID because in your routes.rb
you choose url /create
, in which you have not specified any placeholder for id
. 您的params [:id]之所以不返回Post ID的原因,是因为在您的routes.rb
选择了url /create
,其中您没有为id
指定任何占位符。
if you want something like params[:id]
then in your routes.rb
you should write '/create/:id'
in match
mathod. 如果你想要像params[:id]
,然后在你routes.rb
你应该写'/create/:id'
在match
马托。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.