我有一个带有两个下拉列表的rails应用程序。当第一个选择“作者”时,它会进行ajax调用以检索作者的书。自动预订电话。
在我的javascript中:$.ajax(type: 'GET', url: myadress)
。
它呈现.js.erb
文件:
var dropdown = "<%= escape_javascript(select_tag :author_book, options_from_collection_for_select(@books, :id, :serial), id: 'serial') %>";
var nextDiv = $('#author_book').next();
if(nextDiv.hasClass('select2')) {
nextDiv.remove();
}
$('#author_book').remove();
$('#author').next().after(dropdown);
$('#author_book').select2();
haml文件如下所示:
#author
= simple_form_for :author, url: author_path(store_id: current_store), html: {method: 'post', remote: true, id: nil, class: 'none'} do |f|
#left-scheduled_publications-form
= f.input_field :authors, collection: authors, required: true
%br
= select_tag :author_book, options_for_select([], params[:author_book]), required: true
但它打破了我的dom,它真的很难看。 It seems their is an issue related但也许我错了。
处理此问题的更好方法是什么?是否可以更轻松地替换数据?
答案 0 :(得分:1)
将您的第二个选择放入部分:
<强> _author_book.haml.erb 强>
= select_tag :author_book, options_from_collection_for_select(@books, :id, :serial), id: 'serial')
在视图中为动态内容添加封闭的div
:
#author
= simple_form_for :author, url: author_path(store_id: current_store), html: {method: 'post', remote: true, id: nil, class: 'none'} do |f|
#left-scheduled_publications-form
= f.input_field :authors, collection: authors, required: true
.author-books
= select_tag :author_book, options_for_select([], params[:author_book]), required: true
在你的JS回复中:
$(".author-books").replaceWith("<%= escape_javascript(render: 'author_book') %>");
$('#author_book').select2();
理想情况下,您也希望将部分包含在表单的初始呈现中,您可以通过将@books
设置为空数组来完成。