2010-08-17 39 views
0

我想開發一個ajax功能來評論我網站上的帖子。Rails嘗試執行更新操作而不是我想要的操作

我以前做過這個,但我不知道爲什麼我這次有問題。 Rails從posts_controller執行Update動作,而不是稱爲「save_comment」的動作。

這是我的路線文件的相關行:

map.connect "/posts/save_comment", :controller => 'posts', :action => 'save_comment' 

這是視圖代碼:

<%= javascript_include_tag "prototype" %> 

<% if logged_in? %> 
    <% remote_form_for :post, PostComment.new, :url => {:action => 'save_comment',:post_id=>inside_list.id}, :html => { :method => :put} do |f| %> 
    <p> 
     <%= f.label 'Comment' %><br /> 
     <%= f.text_area :comment, :style=>'height:100px;' %> 
    </p> 
    <p> 
     <%= f.submit 'Publish' %> 
    </p> 
    <% end %> 
<% end %> 

的save_comment動作看起來是這樣的:

def save_comment 
    comment = PostComment.new 
    comment.user_id = current_user.id 
    comment.post_id = params[:post_id] 
    comment.comment = params[:post][:comment] 
    comment.save 

    post = Post.find(params[:post_id]) 

    render :update do |page| 
     page.replace_html 'dComments', :partial => 'post_comments/inside_list', :object => post 
     end 
    end 

BTW:有沒有更好的方法來做到這一點?

+0

什麼的'save_comment'動作是什麼樣子? – 2010-08-17 19:22:06

+0

我已經編輯了該信息的帖子 – 2010-08-17 19:24:14

回答

2

您需要定義路線方法。你也沒有定義post參數。

map.connect "/posts/:post_id/save_comment", :controller => 'posts', :action => 'save_comment', :method => :post 

遵循慣例,您應該使路線方法=>:post,而不是:put。放置請求通常用於更新現有記錄,發佈後用於創建新記錄。還有如何命名路線?

#routes.rb 
map.save_comment "/posts/:post_id/save_comment", :controller => 'posts', :action => 'save_comment', :method => :post 

#view 
<% remote_form_for :post, PostComment.new, :url => save_comment_path(inside_list.id) do |f| %> 

而且,在這裏猜測,但你有沒有這樣定義:

map.resources :posts 

如果你再添加新的方法

map.resources :posts, :member => {:save_comment => :post} 
+0

這個伎倆!謝謝。 – 2010-08-17 19:41:04

+0

de nada! Saludos。 :) – mark 2010-08-17 19:44:10

相關問題