问题描述:

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.

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!

网友答案:

Try:

<% current_user.meta_accounts.select(&:persisted?).each do |meta_account| %>
  <%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
网友答案:

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.

相关阅读:
Top