CommentController #create中的ActiveRecord :: AssociationTypeMismatch

我一直得到Post预期,得到String错误。 如果有人可以提前帮助我。

{:controller=>"comments", :action=>"create"} do |f|%> 


@post.id %>

def create @comment = Comment.create(params[:comment]) if @comment.save redirect_to(:controller=>"posts" ,:action=>'index') else redirect_to(:controller=>"posts" ,:action=>'show', :id=>"post.id") end end

你的第二个重定向应该是:

 redirect_to(:controller=>"posts" ,:action=>'show', :id=> @comment.post.id) 

虽然,看看这个,你肯定可以使用一些更好的模式来清理东西。 如果您使用RESTful路由,我会将您的创建操作更改为:

 def create @post = params[:id] @comment = @post.comments.build(params[:comment]) if @comment.save redirect_to posts_url else redirect_to post_url(@post) end end 

这将允许您删除表单中的隐藏字段,因为它应该作为ID传递给URL。

首先,你不应该将post.id更改为@post.id (并且可能会创建一个post对象)吗?