# Editing multiple models in one form

**URL:** <https://www.ruby-forum.com/t/editing-multiple-models-in-one-form/112609>\
**Category:** Rails\
**Created:** [August 21, 2007, 11:43am UTC](https://www.ruby-forum.com/t/editing-multiple-models-in-one-form/112609 "2007-08-21T11:43:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![nanouk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/da6949/32.png) [@nanouk](https://www.ruby-forum.com/u/nanouk)\
**Post date:** [August 21, 2007, 11:43am UTC](https://www.ruby-forum.com/t/editing-multiple-models-in-one-form/112609/1 "2007-08-21T11:43:03Z")

</div>

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| %\> &nbsp;&nbsp;&nbsp;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?
