0

I have this part of code:

<% current_user.meta_accounts.each do |meta_account| %>
    <%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>

So, I want Rails to show all my MetaAccounts in list, but I get this:

<li><a href="javascript:void(0)">Wallet</a></li>
<li><a href="javascript:void(0)">Credit card</a></li>
<li><a href="javascript:void(0)">Debit card</a></li>
<li><a href="javascript:void(0)">Debts</a></li>
<li><a href="javascript:void(0)">javascript:void(0)</a></li> #This is the problem

So, it also shows me MetaAccount, which isn't created yet.

In my MetaAccounts table I have this. I'm using Postgres.

enter image description here

So, it also shows me the last row, where row_number is *. I don't know why, and how to avoid this.

Thanks for any help!

Peter Tretyakov
  • 3,380
  • 6
  • 38
  • 54

2 Answers2

1

The * row you see in PostgreSQL is not an actual record, it's just a quick way to create new records. If you want to be sure, run the following query:

SELECT COUNT(*) FROM MetaAccounts WHERE user_id=1

It will return 4.

I think the problem comes from an unsaved MetaAccount object in current_user.meta_accounts. This could be the case for instance in a form, where you build an empty object bound to the form. Make sure you don't have a call to current_user.meta_accounts.build(...).

If so, you can simply skip in your each loop all MetaAccount objects with a blank name.

jibai31
  • 1,663
  • 18
  • 22
  • In my `meta_accounts_controller` I'm using this: `def create @meta_account = current_user.meta_accounts.build(params[:meta_account])` There're no MetaAccount `build` in other parts of my app. – Peter Tretyakov Aug 31 '13 at 13:00
  • But `current_user.meta_accounts.where('user_id = ?', current_user.id).each` helped. Thanks! – Peter Tretyakov Aug 31 '13 at 13:04
1

Try:

<% current_user.meta_accounts.select(&:persisted?).each do |meta_account| %>
  <%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497