2013-07-10 27 views
11

我在视图中有两个下拉列表,我试图根据第一个下拉列表中选定的值更新第二个下拉选项。使用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 %> 

所以最后一部分显然是非常错误的,但是那是什么,我试图做的概念。什么是完成这个的正确方法?如有需要,我愿意重新修改,欢迎任何帮助。

+0

你有这个GitHub的仓库?也许对于Rails 4? –

回答

18

添加escape_javascript以逃离运营商退货,单引号和双引号产生的options_from_collection_for_select

我除了给escape_javascript添加呼叫外,没有看到任何其他问题。请尝试在js.erb如下:

<% if @filterProducts %> 
    $('#product_id').html("<%= escape_javascript options_from_collection_for_select(@products, :id, :name) %>"); 
<% end %> 
+1

哇。我是如何忽略这一点的:-)还需要在html()中用引号将嵌入的ruby调用包装起来。谢谢! – Drew

+0

@德鲁,是的,你去了,我已经更新了我的答案加引号。 – vee

+0

你有这个github存储库吗?也许对于Rails 4? –