我有这些模型
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&#39;对于nil:NilClass在这一行:
<td><%= auto.cliente.nombre %></td>
很少在show view中我打电话
@auto.cliente.nombre
工作正常,你能帮帮我吗?谢谢
答案 0 :(得分:0)
似乎<td><%= auto.cliente.nombre %></td>
无效,因为auto.cliente
为nil
,您无法在nombre
上调用该方法nil
。也许您的一个自动对象没有关联的客户端?
要了解这是如何发生的,请尝试在Ruby中运行nil.hello
,您应该会看到一个错误消息为undefined method 'hello' for nil:NilClass
的NoMethodError。
答案 1 :(得分:0)
auto.cliente.try(:nombre)
会让您免于错误,如果您偶然允许自动没有客户。