Problems with belongs_to when using Ajax in Rails 4

4

I have three models in my application, Order , Product and Items . Within Items I have the following code:

class Item < ActiveRecord::Base
  belongs_to :product
  belongs_to :order
end

I have a form where I add a new Order , then I'm redirected to the view 'show.html.erb', where I have an ajax form to add the items, with fields to insert the products referring to these items , as follows:

<%= form_for [@order, @order.items.build], remote: true do |f| %>

And a listing of these items / products. It's in this listing that I'm having problems: I want my list to have the following code:

    <% @order.items.each do |i| %>
<tr>
    <td><%= i.product.name %> </td>
</tr>
<% end %>

However, a rendering error is thrown, saying that the name method does not exist for null object, and I need to refresh the page to work. But, if I change this line to this \:

<td><%= i.product_id %> </td>

Rendering is done correctly.

Given this error, I believe the problem is directly related to the json return of my @item object. But I have no idea how to solve it, can anyone help me?

    
asked by anonymous 12.02.2014 / 00:52

3 answers

1

You can "cheat" the error by adding a if i.product to your listing:

 
<td><%= i.product.name if i.product %></td>

The problem stops, but does not explain why. This has happened to me a few times as well.

    
12.02.2014 / 11:22
0

I think the problem is in your controller .

When you refresh, call the show in controller , @ordem is created, then all information is loaded. After adding the item, you must re-create the variable, or rails will use the cache information.

Another common thing is to create a partial _itens.js.erb for the list, and you resend it again using a response format.js:

$("#itens-index").html("<%= escape_javascript( render 'itens/itens' )%>");
    
14.02.2014 / 19:19
0

Most likely your item has an ID of a product that has already been deleted.

I assume the following also does not work:

<td><%= Product.find(i.product_id) %> </td>
    
12.02.2014 / 01:12