I'm using Rails 4 and trying to access a hash variable via string names.
For example, let's say I have policy model with a member hash who has the fields name and address.
I would like to be able to convert policy_member_name into policy[:member][:name].
However, this string may be longer than just 3 sections. I was able to access the value, but not be able to set it using the following:
ret = obj
keys.each do |key|
ret = ret[key.to_sym]
end
ret
where keys would be an array such as ['member', 'name'] and obj would be the object, such as Policy.first. However, this method only would return what value is at policy[:member][:name] and does not allow me to do policy[:member][:name]=.
Any help is appreciated, thanks.
EDIT:
I'd like to be able to call policy.member_name to get policy[:member][:name] and have policy.member_name= "Something" to set policy[:member][:name]="Something"
method_missing... also, it might be more confusing than helpful - for instance, what happens when:policy.member = Users.find(1); policy.member_name = 'Joe'; puts policy.member...?best_in_placein order to edit fields in place. Are you suggesting not usingOpenStructsat all or simply that the dot notation isn't necessary? Or are you aware of another way to editOpenStructsin place? Thanks!