Problems with belongs_to when using Ajax in Rails 4

Asked

Viewed 131 times

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 one Order, then I am redirected to the 'show.html.erb' view, where I have an ajax form to add the items, with fields to insert the products related to these items, as follows:

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

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

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

But a rendering error is released, saying that the method name does not exist for null object and, it is necessary that I update the page to work. But, if I change this line to that \:

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

Rendering is done correctly.

In view of this error, I believe the problem is directly linked to the json return of my object @item. But I have no idea how to solve, someone can help me?

  • Error only gives when you add a new item per ajax? If you update the page works?

3 answers

1


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

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

The problem does not occur, but it does not explain why. It has happened to me a few times too.

  • 3

    In this case you can use the Try method: i.product.try(:name)

  • Thanks guys, solved my problem, but why do I have to do this? Why he can’t "connect" directly with the object in question?

  • I have the feeling that comes a null item in return ajax... can give a console.log in return?

0

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

I guess the following doesn’t work either:

<td><%= Product.find(i.product_id) %> </td>
  • It doesn’t work either, but the product does, if it didn’t exist, it wouldn’t work when updating the page. It does not work following the execution of ajax. Look at the error that is generated: ActionView::Template::Error (undefined method name' for nil:Nilclass): 1: <% @order.items.each do |i| %> 2: <tr> 3: <td><%= i.product.name %> </td> 4: <td></td> 5: </tr> 6: <% end %>`

0

I believe the problem is in your controller.

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.