Reputation: 735
Hi I have a character
form with fields_for skill_of_objects
nested attribute.
Some skills are generate based on the fixed number of skills_of_objects
that need to be added to the character. And loop like this generates input name and id values correctly.
<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" />
and so on... as long as this is done in the main iteration, it gives proper index number.
But when I make ajax append fields_form, I'm creating new f
builder:
<%= form_for [current_user, @character] do |f| %>
$('#skill_list').append("<%= j render partial: 'add_skill', locals: { character: @character, skill: @skill, f: f } %> ");
<% end %>
And along with this I loose proper index value, and appended partial generates input with 0 index:
<input value="244" type="hidden" name="character[skill_of_objects_attributes][0][skill_id]" id="character_skill_of_objects_attributes_0_skill_id" />
Problem:
How to set corrct value of this input field.
Upvotes: 0
Views: 256
Reputation: 735
I ended in striping index value in my coffeescript action:
name = $('#skill_list li.skill:last input').attr('name')
index = name.replace /[^0-9]/g, ''
I pass it as parameter, incremented it, and generate proper id
, and name
in my append partial.
%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"
Upvotes: 0