2011-10-17 58 views
0

在瀏覽器地址欄中,我有http://localhost:3000/comment/index?post_id=6,我可以訪問索引中的post_id,但是當嘗試在創建操作中創建評論/發佈時,它說不能在日誌中找到沒有帖子ID的帖子。這裏發生了什麼?先謝謝你。:id在那裏,但我不能訪問它,這怎麼可能?

評論控制器:

def index 
    @post=Post.find(params[:post_id]) 
end 

def create 
    @post  = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:comment]) 
    @comment.save 

    respond_with(@comment, :layout => !request.xhr?)   
end 

comments/index觀點:

<%= form_for :comment, :remote => true, 
         :url => { :controller => "comments", 
           :action  => "create" 
           }, 
         :html => { :id => 'new-comment'} do |f| 
%> 
    <%= f.hidden_field :post_id, :value => @post.id %> 
    <%= f.text_area :body %> 
    <%= f.submit "post" %> 
<% end %> 

在日誌:

Started POST "/comments" for 127.0.0.1 at 2011-10-17 14:06:36 -0700 
    Processing by CommentsController#create as JS 
    Parameters: {"utf8"=>"✓", 
    "authenticity_token"=>"cxQm2K2xwsyw0DY2XLNvkcMQI+wM96LpEENbfQqxu5c=", 
    "comment"=> {"post_id"=>"6", "body"=>"This is the comment"}, 
    "commit"=>"post"} 
    Completed 404 Not Found in 23ms 

    ActiveRecord::RecordNotFound (Couldn't find Post without an ID): 

回答

4

如果走在params哈希表來看看在你的日誌,你」看到這個:

{ "utf8"=>"✓", 
    "authenticity_token"=>"cxQm2K2xwsyw0DY2XLNvkcMQI+wM96LpEENbfQqxu5c=", 
    "comment"=> { 
     "post_id"=>"6", # <-- there's your post_id 
     "body"=>"This is the comment" }, 
    "commit"=>"post" } 

所以帖子ID在那裏,但它在comment散列內。因此,在您的創建操作中,您只需更改爲:

def create 
    @post=Post.find(params[:comment][:post_id]) 
    @comment = @post.comments.build(params[:comment]) 
    @comment.save 
    respond_with(@comment, :layout => !request.xhr?)   
end 

但是,您應該能夠簡化創建操作。

def create 
    @comment = Comment.new(params[:comment]) 
    @comment.save 
    respond_with(@comment, :layout => !request.xhr?) 
end 

由於post_idcomment參數,可以在評論會自動用,當你創建帖子相關聯,而無需查找記錄。如果您需要在視圖中訪問該帖子,則可以使用@comment.post

+0

謝謝艾米莉,這非常有幫助 – katie

1

請不要通過您的字段作爲hidden_field的形式。一個更好的方式來做到這將是這樣的:

<%= form_for :comment, 
      :remote => true, 
      :url => post_comments_path(post) 
      :html => { :id => 'new-comment'} do |f| %> 

通過使用路由助手Rails所爲您提供,這將清理您的形式是:

  1. 由於沒有使用醜散列語法來爲您的表單生成URL
  2. 您不需要在窗體中放置一個hidden_field以通過URL發送;和
  3. 自動發送後通過參數params[:post_id]就像上帝 DHH打算。

這意味着你就可以用下面這行代碼來發現它在你的行動:

Post.find(params[:post_id]) 

比這更確切地說,這是不必要的時間更長,因此更痛苦鍵入:

Post.find(params[:comment][:post_id]) 
相關問題