EastsideDev
EastsideDev

Reputation: 6639

Gracefully jumping to next record - ActiveRecord

Rails 3.2

I have the following in my view:

<% @organizations.each do |o| %>
  <% organization = Organization.find(o.organization_id)  %>
    <% if organization == nil %>
      <% next %>
    <% end %>
  <tr>
    <td><%= o.org_name %></td>
    <td><%= number_to_currency(o.revenue, :precision => 0) %></td>
    <td><%= o.rank %></td>
  </tr>
<% end %>

I was under the impression that if organization is not found, execution would jump to the next record. Instead, I am getting the "something went wrong".

Looking through the log file, one of the organization_id is not found in the organizations table, and that's what's triggering the error.

Why isn't execution jumping to the next record?

Temporary Solution: I changed

<% organization = Organization.find(o.organization_id)  %>

To:

<% organization = Organization.find_by_id(o.organization_id)  %>

and that gives me a nil when it does not find anything. If it's nil, the execution skips to the next record

Upvotes: 1

Views: 62

Answers (1)

radhika
radhika

Reputation: 534

According to http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find, Organization.find(o.organization_id) will raise an ActiveRecord::RecordNotFound for the id that does not exist in the table.

Addendum:

Try something like the following:

<% ids = @organizations.map(&:organization_id) %>
<% organizations = Organization.where(id: ids) %>
<% organizations.each do |o| %>
    <tr>
        <td><%= o.org_name %></td>
        <td><%= number_to_currency(o.revenue, :precision => 0) %></td>
        <td><%= o.rank %></td>
    </tr>
<% end %>

With this method, you'll fetch all the organizations with 1 query from the DB as opposed to 1 for every organization.

Upvotes: 2

Related Questions