我有一个像这样创建的对象的实例:
Example.create(:attrib0 => {
:attrib1 => value,
:attrib2 => [
{:attrib3 => value},
{:attrib4 => value}
]
})
我怎样才能访问:attrib4
?
我有一个像这样创建的对象的实例:
Example.create(:attrib0 => {
:attrib1 => value,
:attrib2 => [
{:attrib3 => value},
{:attrib4 => value}
]
})
我怎样才能访问:attrib4
?
您应该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
然而,上面的内容可能会变得非常复杂和丑陋,这就是为什么我建议为这些属性创建另一个模型。
我认为你应该使用嵌套属性。它是这样的:
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} ]
仅使用 Ruby 技术:
h = {:attrib0 => {
:attrib1 => :value1,
:attrib2 => [
{:attrib3 => :value2},
{:attrib4 => :value3}
]
}}
p h[:attrib0][:attrib2].last[:attrib4] #=> :value3