0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Works, but usernames are now shown, I think it got invalid data, and you are right about has_many/belongs to that is really what I am doing, So how Rails can handle that for me, what should I do?
This Rails Guide will get you off to a good start guides.rubyonrails.org/association_basics.html. You'll have to rails g migration AddCompanyIdToUsers company_id:integer, then add has_many :users and belongs_to:company in the appropriate models. To point a user at the company, set "@user.company_id = @company.id". Rails knows that if there's an attribute XXXXX_id it's meant for the association and will use that to figure things out.
Thank you very much and I appreciate your detailed help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.