2010-11-22 43 views
0

我不斷收到郵政預期,得到字符串錯誤。如果有人可以提前幫助我。ActiveRecord :: AssociationTypeMismatch CommentsController#創建

<% form_for :comment, :url=>{:controller=>"comments", :action=>"create"} do |f|%> 
<p> 
<%= f.label :body, "New Comment"%><br /> 
<%= f.text_area :body %> 
<%= f.hidden_field :post, :value=>@post.id %> 
</p> 
<p><%= f.submit "Add Comment"%></p> 
<% end%> 

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 

回答

0

首先,你不應該改變post.id@post.id(也許創建一個對象後)?

1

你的第二個重定向應該是:

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

雖然,看着這個,你肯定可以使用一些更好的方式來清理東西。如果您正在使用REST風格的路線,我會改變你的創建操作是:

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 

這將讓你因爲它應該通過URL作爲ID來獲得通過刪除表單中的隱藏字段。

+0

這幫了我很多,謝謝! :) – okoronkwo 2010-11-23 12:10:58

相關問題