开发者

Rails Hash with several object attributes. How do I save them all?

开发者 https://www.devze.com 2022-12-19 04:18 出处:网络
I get hash from a fields_for that looks like this: \"affiliation_attributes\"=>{ \"11\"=>{\"volunteer_id\"=>\"14\", \"affiliationtype_id\"=>\"1\", \"organization_id\"=>\"1\"},

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 attri开发者_StackOverflow中文版butes of it.

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

Thanks in advance.


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 => )


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消