2013-07-10 31 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? –