简体   繁体   中英

Ruby on rails NoMethodError active record

I have these models

class Auto < ApplicationRecord
  belongs_to :marca
  belongs_to :modelo
  belongs_to :cliente  
end

class Cliente < ApplicationRecord  
  has_many :autos
end

class Marca < ApplicationRecord
  has_many :modelos
  has_many :autos
end

class Modelo < ApplicationRecord
  belongs_to :marca
  has_many :autos
end

and this index view

<table class="table table-striped" id="autos">
  <tr>
    <th>Id</th>
    <th>Cliente</th>
    <th>Marca</th>
    <th>Modelo</th>
    <th>Placas</th>
  </tr>
  <% @auto.each do |auto| %>
  <tr>
      <td><%= auto.id %></td>
      <td><%= auto.cliente.nombre %></td>
      <td><%= auto.marca.nombre%></td>
      <td><%= auto.modelo.nombre %></td>
      <td><%= auto.placas %></td>
  </tr>
  <% end %>
</table>

and this in my autos controller

def show
 @auto = Auto.find(params[:id])    
end

def index
 @auto = Auto.all    
end

the problem is that show me this error: undefined method `nombre' for nil:NilClass in this line:

<td><%= auto.cliente.nombre %></td>

rarely at show view where I call

@auto.cliente.nombre 

works fine, can you help me? thanks

It seems like <td><%= auto.cliente.nombre %></td> doesn't work because auto.cliente is nil , and you cannot call that method nombre on nil . Perhaps one of your auto objects doesn't have an associated client?

To see how this happens, try running nil.hello in Ruby and you should see a NoMethodError with the error message undefined method 'hello' for nil:NilClass .

如果您偶然允许不带cliente的auto,则auto.cliente.try(:nombre)将使您免于错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM