访问hashmap作为对象的属性

时间:2013-04-21 12:16:22

标签: ruby-on-rails ruby

我有一个像这样创建的对象实例:

Example.create(:attrib0 => {
  :attrib1 => value,
  :attrib2 => [
    {:attrib3 => value},
    {:attrib4 => value}
    ]
})

如何访问:attrib4

3 个答案:

答案 0 :(得分:2)

您应该在模型中使用serialize,然后您才能正确返回哈希:

class SomeModel < ActiveRecord::Base
  serialize :attrib0
end

然后以下内容应该返回哈希

hash  = @model.attrib0
# => {:attrib1 => value, :attrib2 => [{:attrib3 => value}, {:attrib4 => value}]

# now to access attrib4 you need to get the attrib2 array,
# then grab attrib4 by its index:
hash[:attrib2][1]
# => {:attrib4 => value}

# or to get the value:
hash[:attrib2][1][:attrib4]
# => value

然而,上面的内容会非常复杂和丑陋,这就是我建议为这些属性创建另一个模型的原因。

答案 1 :(得分:1)

我认为你应该使用nested attributes。这是它的方式:

class Example
  has_one :attrib0

  accepts_nested_attributes_for :attrib0
end

params = { :attrib0 => { :attrib1 => value1, 
  :attrib2 => [ {:attrib3 => value3}, {:attrib4 => value4} ] }
}

example = Example.create(params[:attrib0])
example.attrib0.attrib1 #=> value1
example.attrib0.attrib2 #=> [ {:attrib3 => value3}, {:attrib4 => value4} ]

答案 2 :(得分:0)

仅使用Ruby技术:

h = {:attrib0 => {
  :attrib1 => :value1,
  :attrib2 => [
    {:attrib3 => :value2},
    {:attrib4 => :value3}
    ]
}}

p h[:attrib0][:attrib2].last[:attrib4] #=> :value3