Reputation: 12653
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
Upvotes: 3
Views: 1622
Reputation: 15771
<%- @model.data[:attr1] %>
Replace with:
<%= @model.data["attr1"] %>
NOTE: <%=
at the beginning. You've used <%-
mistakenly.
UPD:
I recommend to use the HashWithIndifferentAccess
:
serialize :data, HashWithIndifferentAccess
This way you can fetch your values via symbols or strings as the key.
Upvotes: 8