2013-10-02 30 views
1

在一個Rails 3.2應用程序我有與一個「選擇了」數據屬性返回的ID號的陣列從元件的CoffeeScript功能。如何使用coffeescript和數據屬性生成params數組?

#view (pseudo code!) 
<table id='elems_container' data-url=<%= my_path(@object%) > 
    <tr data-selected = 'true' data-id = '1'></tr> 
    <tr data-selected = 'true' data-id = '2'></tr> 
    <tr data-selected = 'false' data-id = '3'></tr> 
    <tr data-selected = 'true' data-id = '4'></tr> 
</table> 

#coffeescript 
elems = $("tr[data-selected='true']").map(-> 
    $(this).data "id" 
).get() 
$.ajax({ url: $('#elems_container').data('url'), dataType: "script", data: { 'selected_ids': elems } }) 

這將返回在日誌下面

Started GET "/my/path?selected_ids%5B%5D=1&selected_ids%5B%5D=2&selected_ids%5B%5D=4 

我現在要選擇控制器這些選定IDS

@collection = Model.where('id = ?', params[:selected_ids]) 

這實際上是返回所有車型,而不僅僅是在對上市女士。

get URL是否正確,或者params數組看起來不一樣?我還有什麼做錯了?

回答

2

如果URI解碼您的查詢字符串,你會看到這一點:

selected_ids[]=1&selected_ids[]=2&selected_ids[]=4 

當Rails的看到支架,[],它會創建params[:selected_ids]數組從查詢字符串,你拿着值將有['1','2','4']params[:selected_ids]

當你有多個值來檢查,你想要的SQL是:

where id in (1,2,4) 

ActiveRecord的是足夠聰明的使用in操作,當你把它像這樣的數組:

where(:some_column => some_array) 

所以你應該可以這樣說:

@collection = Model.where(:id => params[:selected_ids]) 

並得到你在找什麼f或在@collection

+0

不敢相信我忽略了'in'SQL查詢!感謝您的好解釋。 –

相關問題