如何设置ajax的索引附加嵌套fields_for表单

时间:2016-06-03 04:16:59

标签: ruby-on-rails ajax fields-for

您好我有character表单,其中包含fields_for skill_of_objects嵌套属性。

根据需要添加到角色的skills_of_objects的固定数量生成一些技能。像这样的循环正确生成输入名称和id值。

<input value="224" type="hidden" name="character[skill_of_objects_attributes][0][skill_id]" id="character_skill_of_objects_attributes_0_skill_id" />
<input value="23" type="hidden" name="character[skill_of_objects_attributes][1][skill_id]" id="character_skill_of_objects_attributes_1_skill_id" />
<input value="248" type="hidden" name="character[skill_of_objects_attributes][2][skill_id]" id="character_skill_of_objects_attributes_2_skill_id" />

依此类推......只要在主迭代中完成,它就会给出正确的索引号。

但是,当我将ajax附加到fields_form时,我正在创建新的f构建器:

<%= form_for [current_user, @character] do |f| %>
  $('#skill_list').append("<%= j render partial: 'add_skill', locals: { character: @character, skill: @skill, f: f } %> ");
<% end %>

与此同时,我松散了正确的索引值,并且附加的部分生成了带有0索引的输入:

<input value="244" type="hidden" name="character[skill_of_objects_attributes][0][skill_id]" id="character_skill_of_objects_attributes_0_skill_id" />

问题:

如何设置此输入字段的corrct值。

1 个答案:

答案 0 :(得分:0)

我在我的coffeescript动作中删除了索引值:

name = $('#skill_list li.skill:last input').attr('name')
  index = name.replace /[^0-9]/g, ''

我将其作为参数传递,递增,并在我的附加部分中生成正确的idname

%li.skill{ id: "skill_#{skill.name_pl.squish.tr(' ','_')}"}
  = f.fields_for :skill_of_objects, character.skill_of_objects.build do |ff|
    %strong
      = skill.name_pl
    = ff.hidden_field :skill_id, value: skill.id, name: "character[skill_of_objects_attributes][#{index}][skill_id]", id: "character_skill_of_objects_attributes_#{index}_skill_id"