views:

124

answers:

2

I get hash from a fields_for that looks like this:

"affiliation_attributes"=>{
"11"=>{"volunteer_id"=>"14", "affiliationtype_id"=>"1", "organization_id"=>"1"},

"1"=>{"volunteer_id"=>"1", "affiliationtype_id"=>"3", "organization_id"=>"1"}, 

"4"=>{"volunteer_id"=>"2", "affiliationtype_id"=>"3", "organization_id"=>"1"}, 

"21"=>{"volunteer_id"=>"20", "affiliationtype_id"=>"1", "organization_id"=>"1"}

The first number ( like the 11 ) is the affiliationtype_id and the values next to it are the attributes of it.

What I want to do is to save all those Affiliationtypes. How can I do that?

Thanks in advance.

A: 

Well, I've found a way but it's a temporary hack!

I've made a method that does this:


 affiliation_attributes.each do |attributes|

      a = Affiliation.find_by_id(attributes[0])
      a.volunteer_id = attributes[1]["volunteer_id"]
      a.organization_id = attributes[1]["organization_id"]
      a.affiliationtype_id = attributes[1]["affiliationtype_id"]
      a.save

  end

How can I make this better? Thanks.

Victor Martins
A: 

You need "accept_nested_attributes_for".

If you're doing your forms the usual style, you should watch "Complex Forms" 1 to 3 from railscasts.com, this case is handled there. http://railscasts.com/episodes/73-complex-forms-part-1 http://railscasts.com/episodes/74-complex-forms-part-2 http://railscasts.com/episodes/75-complex-forms-part-3

Or if you want to go the easy way, use formtastic and this is handled for you ;-) http://github.com/justinfrench/formtastic (read about the examples with :for => )

pduersteler