繁体   English   中英

具有多个对象属性的Rails Hash。 如何保存它们?

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

我从fields_for获得哈希,如下所示:

"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"}

第一个数字(如11)是affiliationtype_id,其旁边的值是其属性。

我要做的是保存所有这些从属类型。 我怎样才能做到这一点?

提前致谢。

好吧,我找到了一种方法,但这只是暂时的破解!

我已经做了一个可以做到这一点的方法:


 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

我该如何做得更好? 谢谢。

您需要“ accept_nested_attributes_for”。

如果您按常规样式制作表单,则应在railscasts.com上观看“复杂表单” 1到3,这种情况在此处处理。 http://railscasts.com/episodes/73-complex-forms-part-1 http://railscasts.com/episodes/74-complex-forms-part-2 http://railscasts.com/episodes/75-复杂形式第3部分

或者,如果您想采用简单的方法,请使用formtastic,这将为您处理;-) http://github.com/justinfrench/formtastic (阅读有关:for =>的示例)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM