[英]Ruby on rails NoMethodError active record
我有這些模特
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
問題是,向我顯示此錯誤:此行中nil:NilClass的未定義方法'nombre':
<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
的錯誤消息undefined method 'hello' for nil:NilClass
。
如果您偶然允許不帶cliente的auto,則auto.cliente.try(:nombre)
將使您免於錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.