假设表单用于Order
模型,并且您正在parts
根据名为 的字段的值更改集合region
。
更新表单视图。指定表单、region
字段和parts
字段的 ID。
= simple_form_for(@order, :html => { :id => "order-form"}) do |f|
= f.input :region, :wrapper_html => { :id => "order-form-region", |
"data-parts-url" => parts_orders_path(:id => @order.id, :region => @order.region)} |
= f.input :parts, as: check_boxes, collection: @parts_list, |
:wrapper_html => { id' => 'parts-check-box-list'} |
parts
添加在route.rb
文件中调用的新操作。
resources :orders do
collection do
get :parts
end
end
将新操作添加到您的控制器
class OrdersController < ApplicationController
# expects id and region as parameters
def parts
@order = params[:id].present? ? Order.find(params[:id]) : Order.new
@parts_list = Part.where(:region => params[:region])
end
end
添加助手
def parts_collection(order, parts_list)
"".tap do |pc|
# to generate the markup for collection we need a dummy form
simple_form_for(order) do |f|
pc << f.input(:parts, as: check_boxes, collection: parts_list,
:wrapper_html => {:id => 'parts-check-box-list'})
end
end
end
为动作添加一个 js 视图 ( orders/parts.js.erb
)
$('#parts-check-box-list').replaceWith('<%= j(parts_collection(@order, @parts_list)) %>');
region
为您的字段注册数据更改事件处理程序application.js
$(document).ready(function() {
$('#order-form').on("change", "#order-form-region", function () {
// Access the data-parts-url set in the region field to submit JS request
$.getScript($(this).attr('data-parts-url'));
});
});