我在视图中有两个下拉列表,我试图根据第一个下拉列表中选定的值更新第二个下拉选项。使用rails中的ajax动态更新选择标记
我知道关于这个主题的Railscasts,但我不想使用分组集合;原因主要在于用户可以从一个下拉列表中选择一个,或者另一个下拉列表中的结果进行相应的筛选,第二个下拉菜单只有在选择第一个下拉菜单中的值时对其选项进行筛选。
我的问题是,我如何重新从js.erb文件中填充select_tag选项?
形式
<%= form_tag("filter", :id => "filter_form", :method => "post") do %>
<label for="company_id" class="company">Company</label><%= select_tag(:company_id, options_from_collection_for_select(Company.all.order(:name), :id, :name), :prompt => "All Companies") %>
<label for="product_id" class="product">Product</label><%= select_tag(:product_id, options_from_collection_for_select(Product.all.order(:name), :id, :name), :prompt => "All Products") %>
<% end %>
js.coffee
$('#company_id').change(->
sendFilterForm()
)
sendFilterForm = ->
$.get($('#filter_form').attr('action'), $('#filter_form').serialize(), 'script')
控制器
@filterProducts = true
@products = Product.where(company_id: params[:company_id]).order(:name)
js.erb
<% if @filterProducts %>
$('#product_id').html(<%= options_from_collection_for_select(@products, :id, :name) %>);
<% end %>
所以最后一部分显然是非常错误的,但是那是什么,我试图做的概念。什么是完成这个的正确方法?如有需要,我愿意重新修改,欢迎任何帮助。
你有这个GitHub的仓库?也许对于Rails 4? –