我有这些模型
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
和此索引视图
<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>
这在我的汽车控制器中
def show
@auto = Auto.find(params[:id])
end
def index
@auto = Auto.all
end
问题是向我显示此错误:未定义的方法 'nombre' 对于 nil:NilClass 在此行中:
<td><%= auto.cliente.nombre %></td>
很少在我打电话的显示视图
@auto.cliente.nombre
工作正常,你能帮我吗?谢谢
<td><%= auto.cliente.nombre %></td>
不起作用,因为auto.cliente
是nil
,并且您不能在nil
上nombre
调用该方法。也许您的某个自动对象没有关联的客户端?
要查看这是如何发生的,请尝试在 Ruby 中运行 nil.hello
,您应该会看到一个 NoMethodError 错误消息undefined method 'hello' for nil:NilClass
。
偶然允许没有客户端的自动,auto.cliente.try(:nombre)
将使您免于错误。