Editing multiple models in one form

I’m looking to try and get the edit function working on a page for
editing multiple models within the one form.

I can currently edit any child models of a parent if the child records
already exist, the problem lies with adding extra child records to the
parent record.

My update function currently looks like this:

def update
@script = Script.find(params[:id])
if params[:script_metadatas]
params[:script_metadatas].each_with_index do |value, index|
script_metadata =
@script.script_metadatas.find_or_initialize_by_id(params[:script_metadatas][index.to_s]
? params[:script_metadatas][index.to_s][‘id’] : nil)
if script_metadata.new_record?
@script.script_metadatas.create(params[:script_metadatas][index.to_s])
else
script_metadata.update_attributes(params[:script_metadatas][index.to_s])
end
end
end
end
end

My view is such:

<% form_tag :action => ‘update’, :id => @script do %>


<% @script.script_metadatas.each_with_index do |script_metadata,
index| %>
<%= render :partial => ‘script_metadata_fields’, :locals => {
:script_metadata => script_metadata, :index => script_metadata.id } %>
<% end %>


<%= render :partial => ‘add_script_metadata_link’, :locals => {
:index => @script.new_script_metadata_id } %>




<%= submit_tag ‘Update Metadata Info’ %>

<% end %>

My ‘script_metadata_fields’ partial:

<% fields_for "script_metadatas[#{index}]", script_metadata do |f| %>    Key: <%= f.text_field :meta_key %> Value: <%= f.text_field :meta_value %> <%= link_to_remote 'Remove', :url => { :action => 'remove_script_metadata', :index => index } %> <% end %>

The problem i have is when i submit the data, i get the following error
message:

You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]

All the correct parameters seem to be being passed, however the update
fails on the line beginning ‘params[:script_metadatas].each_with_index
do |value, index|’ in my controller action, and the line immediately
following it.

Can anyone suggest why?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs