我嘗試使用像國家/城市關係這樣的Ajax實現相關的選擇選項菜單。Rails form_helper無法在ajax請求後刻錄「更新」動作
當我嘗試在新視圖和編輯視圖中從_form.html.erb
呈現窗體時。我無法編輯文章,當我在edit.html.erb
,article#create
submited表單中操作燒傷而不是article#update
。
很明顯,Ajax引發了這個問題。但我無法弄清楚如何解決這個問題。
我試圖把表格放在edit.html.erb
而不是像url: { action: "update" }
那樣渲染它並改變表單助手url地址,但後來我遇到了這個錯誤No route matches [POST] "/foo/123"
。
categories/edit.html.erb
<%= form_for :category, url: { action: "update" } do |f| %>
Category 1: <%= f.collection_select(:parent_id, @categories, :id, :name, {:include_blank => 'No Parent'}, { :id => 'C1', name: 'parent[id1]' }) %>
Category 2: <%= f.collection_select(:parent_id, @categories, :id, :name, {:include_blank => 'No Parent'}, { :id => 'C2', name: 'parent[id2]' }) %>
<script>
$(document).ready(function() {
$('#C1').change(function() {
$.ajax({
url: "<%= children_category_path %>",
data: {
id : $('#C1 option:selected').val(),
which : "C1",
form : "categories"
},
dataType: "script"
});
});
$('#C2').change(function() {
$.ajax({
url: "<%= children_category_path %>",
data: {
id : $('#C2 option:selected').val(),
which : "C2",
form : "categories"
},
dataType: "script"
});
});
</script>
get.js.coffee
<% if @class == "C1" %>
$("#C2")
.empty()
<% if @form == "categories" %>
.append("<option value> </option>")
<% end %>
.append("<%= escape_javascript(options_from_collection_for_select(@categories, :id, :name)) %>");
<% end %>
<% if @class == "C2" %>
$("#C3")
.empty()
<% if @form == "categories" %>
.append("<option value> </option>")
<% end %>
.append("<%= escape_javascript(options_from_collection_for_select(@categories, :id, :name)) %>");
<% end %>
categories_controller.rb
def edit
@category = Category.find(params[:id])
@categories = Category.roots
end
def update
@category = Category.find(params[:id])
if @category.update(create_params)
redirect_to categories_path
else
render 'edit'
end
end
children_controller.rb
def get
@class = params[:which]
@form = params[:form]
@categories = Category.find(params[:id]).children
respond_to do |format|
format.js
end
end
當我看到編輯操作的另一個例子。當更新操作燒錄時,有兩個參數method =>「_patch」和action =>「update」。嘗試提交表單時,可能需要添加這些參數。 –