2016-07-04 51 views
0

我對這個參數如何工作有點困惑。比如我想在索引頁創建與選擇標籤的用戶的集合是這樣的:如何從選擇標籤獲取id作爲params?

用戶/ index.html.erb

<%= select_tag "user", options_from_collection_for_select(@users, "id", "name")%> 

<%= link_to "new", new_user_book_path(params[:user]) %> 

我有一個用戶列表下拉,我有鏈接到書籍/新頁面的按鈕。如何將我在下拉菜單中選擇的user id傳遞給'new_user_book_path`?

在此先感謝!

回答

1

你必須爲它寫一些javascript。

<%= select_tag "user", options_from_collection_for_select(@users, "id", "name"), {id: "select_users" } %> 
<!-- If you don't pass id attribute, the default id will be 'user' by convention --> 

<%= link_to "New", new_user_book_path(@users.first.id), id: "btn_book", data: { book_path: new_user_book_path } %> 

當轉換爲純HTML這將是這個樣子

<select name="user" id="select_users"> 
    <option value="1">User1</option> 
    <option value="2">User2</option> 
</select> 

<a id="btn_book" data-book-path="book/new" href="books/new/1">New</a> 

通知我們,我們有與第一用戶的路徑設置,所以如果沒有從選擇下拉選擇時,第一個用戶將被傳遞給params。現在我們將編寫一些腳本來更新所選用戶的路徑。

$(document).ready(function(){ 
    $("#select_users").on('change', function(){ 
    var user = $(this).val(); 
    var path = $("#btn_book").attr("data-book-path"); 
    $("#btn_book").attr('href', path + "/" + user); 
    //#btn_book is the id of our link, where we'll change its href to the selected user 
    }); 
}); 

我假設傳統的代碼,路徑和其他東西可能會改變。根據您的需求進行調整。希望這可以幫助。