[英]How can I get the id from select tag as params?
我对如何使用这些参数感到有些困惑。 例如,我试图在索引页面中使用select标签创建一个用户集合,如下所示:
users / 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”?
提前致谢!
您必须为此编写一些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
});
});
我假设常规代码,路径和其他情况可能会发生变化。 根据需要进行调整。 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.