Reputation: 15863
I have a serialized array of objects of User class:
serialize :members, Array
And here is how its column looks in the database
---
- '1'
- '2'
- !ruby/object:User
attributes:
id: 18
username: bulk7
email: !ruby/string:Spreadsheet::Link
admin: false
locked: false
slug: bulk7
- !ruby/object:User
attributes:
id: 19
username: bulk8
email: !ruby/string:Spreadsheet::Link
admin: false
locked: false
slug: bulk8
I need to loop through each array element and get some info from it in my view:
<ul class="list-group">
<% @user.company.members.each do |m| %>
<li class="list-group-item"><%= m.username%></li>
<% end %>
</ul>
</div>
But instead of getting the proper value I got this error:
undefined method `username' for "1":String
So what is the proper way of de-serializing this object?
Upvotes: 0
Views: 447
Reputation: 365
It looks like you have some stray data in there which is mucking things up. The first thing that's inserted into the block is '1', and then when '1'.username is called your error is thrown. You can sidestep this issue by skipping anything that's not a User:
<ul class="list-group">
<% @user.company.members.each do |m| %>
<% break unless m.class == User %>
<li class="list-group-item"><%= m.username %></li>
<% end %>
</ul>
But that's a really ugly solution and you should probably figure out why you have stray data polluting your database in the first place. I think what you might actually be trying to do is use a has_many/belongs_to association to tie Users to a Company. Instead of using serialize, rails can handle all of the gruntwork for you.
Upvotes: 1