How to get serialized data?

In a Rails 3.2 application, I have a model with a text column :data. In the model, I have:

class Model
  serialize :data, Hash
end

This is the correct storage of data in a format data:{"attr1"=>"foo", "attr2"=>"bar"....}.

If I want to display this in the show view, I can do <%= @model.data %>it and the entire hash will be displayed.

But what if I only need to display a specific attribute? Is it possible?

I tried several approaches that looked as if they could work:

<%= @model.data.attr1 %>- generates undefined method 'attr1' <%- @model.data[:attr1] %>- nothing is displayed

Am I missing something? Thanks for any pointers

+3
source share
2 answers
<%- @model.data[:attr1] %>

Replaced by:

<%= @model.data["attr1"] %>

NOTE: <%=at the beginning. You mistakenly used <%-.

UPD:

HashWithIndifferentAccess:

serialize :data, HashWithIndifferentAccess

.

+8

Hash?

 @model.data['attr1']
+2

All Articles