In a Rails 3.2 app I have a Model with a text column :data. In the model I have:
class Model
serialize :data, Hash
end
This is storing data correctly, in the format data:{"attr1"=>"foo", "attr2"=>"bar"....}.
If I want to display this in a show view I can do <%= @model.data %>, and the entire hash is rendered.
But what if I only need to render a specific attribute? Is this possible?
I’ve tried several approaches that seemed like they might work:
<%= @model.data.attr1 %> – generates undefined method 'attr1'
<%- @model.data[:attr1] %> – displays nothing
Am I missing something?
.
Thanks for any pointers
Replace with:
NOTE:
<%=at the beginning. You’ve used<%-mistakenly.UPD:
I recommend to use the
HashWithIndifferentAccess:This way you can fetch your values via symbols or strings as the key.