构建了一个非常基本的rails应用程序来使用cocoon操作嵌套属性,添加和删除链接效果很好。但是,在我想要更改插入内容的基础内容之前,它不会太长,比如响应另一个字段更改包含的选择标记中的选项值列表。似乎要添加的内容包含在' a'标签数据元素(data-association-insertion-template)。我可以很容易地通过jQuery更改所有包含行的选择选项,但更改link_to_add_association的行为超出了我的范围。
以下是我的例子的片段:
_form.html.erb
<div class="nested-fields">
<%= f.label :item_id %>
<%= f.select :item_id, @items.collect {|i| [i.style, i.id]}, {include_blank: true}, {selected: :item_id, multiple: false} %>
<%= f.label :decoration_id, 'Decoration' %>
<%= f.select :decoration_id, @decorations.collect { |d| [ d.name, d.id ] }, {include_blank: true}, {selected: :decoration_id, multiple: false, class: 'decoration'} %>
<%= f.label :color %>
<%= f.text_field :color %>
<%= f.label :size_id %>
<%= f.select :size_id, @sizes.collect { |s| [ s.name, s.id ] }, {include_blank: true}, {selected: :size_id, multiple: false} %>
<%= f.label :number %>
<%= f.number_field :number, value: 1, min: 1 %>
<%= f.check_box :_destroy, hidden: true %>
<%= link_to_remove_association "Remove Entry", f %>
</div>
_entry_fields.html.erb
ready = ->
$('.customer').change ->
$.ajax
url: '/orders/change_customer'
data: { customer_id : @value }
$(document).ready(ready)
$(document).on('turbolinks:load', ready)
orders.coffee
def change_customer
@decorations = Decoration.joins(:logo).where('logos.customer_id = ?', params[:customer_id])
respond_to do |format|
format.js
end
end
order_controller.rb
// update all existing entry decorations with new customer driven options
<% new_decor = options_from_collection_for_select(@decorations, :id, :name) %>
var new_decor_options = "<option value='' selected='selected'></option>" + "<%=j new_decor %>";
$('.decoration').html(new_decor_options);
// now need to change $('#cocoon-add-entry').attr('data-association-insertion-template, ???);
// or regenerate link entirely - but don't have required data to do so here (form builder from original)
change_customer.js.erb
{{1}}
我试图通过js str.replace直接操作模板数据字符串,但这是一个丑陋的正则表达式,因为unescapeHTML和htmlsafe操作使得它首先成为属性。而且,这种方法对我来说并不好闻。我一直在慢慢地通过cocoon view_helpers和javascript,但似乎没有什么适合,或者我似乎没有正确的方法/数据值来构建替换链接。建议?
BTW,茧宝石的荣誉。答案 0 :(得分:1)
change_customer.js.erb
// update all existing entry decorations with new customer driven options
<% new_decor = options_from_collection_for_select(@decorations, :id, :name) %>
var new_decor_options = "<option value='' selected='selected'></option>" + "<%=j new_decor %>";
$('.decoration').html(new_decor_options);
// update the Add Entry link to capture new decorations set.
// Note use of ugly hack to recreate 'similar' form.
// Also note that this will only work for new order; will have to revise for edit.
'<%= form_for(Order.new) do |ff| %>'
$('#cocoon-add-entry').replaceWith("<%=j render partial: 'add_entry_link', locals: {f: ff} %>");
'<% end %>'
_add_entry_link.html.erb
<%= link_to_add_association 'Add Entry', f, :entries, {id: 'cocoon-add-entry', data: {'association-insertion-method' => 'after'}} %>