[英]Problem with link_to_remote in rails
我在rails中使用link_to_remote時遇到了一致性問題。
我有2個link_to_remote用例,它們生成不同的ajax。 我無法弄清楚為什么,這讓我發瘋。
這是用例一......
<%= link_to_remote "section-", :update => "sections", :url => {:action => :destroy, :controller => "sections", :id => @section.id } %>
這會生成適當的ajax(如下所示)並按預期工作。 請注意,它從調用中獲取:action參數並將其正確插入到ajax中。
<a href="#" onclick="if { new Ajax.Updater('sections', '/sections/destroy/1', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('f5e50e62fafd118e4588b33c9571ea6eef864176')}); }; return false;">section-</a>
我還有另一個實例,我使用link_to_remote,但它生成不正確的ajax。 除了控制器不同之外,用例幾乎相同。 無論哪種方式,我都不希望這導致不同的ajax。
電話......
<%= link_to_remote "question-", :update =>"questions-1", :url => {:action => :destroy, :controller => "questions", :id => @question.id} %>
由此產生的ajax ......
<a href="#" onclick="if { new Ajax.Updater('questions-1', '/questions/1', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('f5e50e62fafd118e4588b33c9571ea6eef864176')}); }; return false;">question-</a>
這里明顯的區別在於Ajax.Updater的第二個arg。 :該路徑中缺少:action param。 為什么? 這會導致我的代碼損壞,但我無法理解為什么會發生這種情況。 link_to_remote調用幾乎相同。
請指出我正確的方向。 謝謝。
下面是我的routes.rb文件......
ActionController::Routing::Routes.draw do |map|
map.resources :questions, :has_one => :section, :collection => { :sort => :post }
map.resources :sections, :has_many => :questions, :has_one => :form, :collection => { :sort => :post }
map.resources :forms, :has_many => :sections
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
map.root :controller => "forms"
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
如果將其復制到視圖中,您會得到什么?
<%= url_for :action => :destroy, :controller => :questions, :id => @question.id %>
我懷疑問題不是真的與link_to_remote,而是與路由 。 一旦url_for返回您期望的URL,然后再次嘗試link_to_remote。
只需在您的link_to_remote調用中添加:method =>:delete可能是最簡單的修復方法:
<%= link_to_remote "question-", :update =>"questions-1", :url => {:action => :destroy, :controller => "questions", :id => @question.id}, :method => :delete %>
這應該強制調用/ questions /:id來使用HTTP DELETE方法。 如果你想讓上面的調用生成url / questions / destroy /:id,我相信你需要手動更改你的路由,因為默認的map.resources似乎沒有達到那個結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.