使用rails中的ajax动态更新选择标记

我在视图中有两个下拉列表,我正在尝试根据第一个下拉列表中的选定值更新第二个下拉选项。

我知道关于这个主题的Railscasts,但我不想使用分组集合; 其原因主要是用户可以从一个下拉菜单或另一个下拉菜单中进行选择,并相应地过滤结果,第二个下拉菜单在选择第一个下拉列表中的值时过滤其选项。

我的问题是,如何从js.erb文件中重新填充select_tag选项?

形成

 "filter_form", :method => "post") do %>  "All Companies") %>  "All Products") %>  

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

  $('#product_id').html();  

所以最后一部分显然是错误的,但这就是我想要做的概念。 完成此任务的正确方法是什么? 如果需要,我愿意重做这件事,感谢任何帮助。

添加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 %>