3

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

4

2 回答 2

8
<%- @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.

于 2012-05-06T11:18:05.350 回答
2

Did you try the string format of Hash key?

 @model.data['attr1']
于 2012-05-06T11:15:00.147 回答