【问题标题】:Rails Hash with several object attributes. How do I save them all?具有多个对象属性的 Rails Hash。我该如何保存它们?
【发布时间】:2010-02-07 00:01:28
【问题描述】:

我从 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 ,它旁边的值是它的属性。

我想要做的是保存所有这些 Affiliationtypes。 我该怎么做?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails forms hash save


    【解决方案1】:

    您需要“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-complex-forms-part-3

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

    【讨论】:

      【解决方案2】:

      好吧,我找到了一个方法,但它是一个临时的 hack!

      我已经做了一个方法:

      
       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
      

      我怎样才能做得更好? 谢谢。

      【讨论】:

        猜你喜欢
        • 2023-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2017-09-09
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        相关资源
        最近更新 更多