2017-07-31 39 views
1

由於某種原因,此頁面不會在rails 5上使用ruby打開。它爲我提供了一個未定義的方法`name'for nil:NilClass error。Rails問題 - 未找到方法'name'

上次打開代碼時,代碼工作正常。任何人都可以請幫忙?非常感謝。

這裏是查看頁面。

<h1> Your sale history page </h1> 
    <table class="table table-bordered table-hover table-striped"> 
    <tr> 
    <th>Image</th> 
    <th>Title</th> 
    <th>Label</th> 
    <th>Condition</th> 
    <th>Customer</th> 
    <th>Price</th> 
    <th>Date Sold</th> 
    </tr> 

    <% @orders.each do |order| %> 
    <tr> 
     <td><%= image_tag order.record.image.url(:thumb)%></td> 
     <td><%= order.record.Title %></td> 
     <td><%= order.record.Label %></td> 
     <td><%= order.record.Condition %></td> 
     <td><%= order.buyer.name %></td> 
     <td><%= order.record.Selling_Price %> </td> 
     <%#THE BELOW CODE IS FOR RUBY DATE. FOUND ON rubydoc%> 
     <td><%= order.created_at.strftime("%-d %B, %Y") %></td> 
     <td> 

    </tr> 
<%end%> 

class User < ApplicationRecord 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
#the below code validates that the name present 
    validates :name, presence: true 

#the below code tells rails that a user has many records. and that if a user is deleted so is the record 
    has_many :records, dependent: :destroy 

    has_many :sales, class_name:"Order", foreign_key: "buyer_id" 

    has_many :reviews, dependent: :destroy 
end 


class Order < ApplicationRecord 
    #the below validates the form fields 
    validates :address,:town_or_city,:state_or_county,:post_or_zip_code,:country, presence: true 

    belongs_to :record 

    # the below code tells rails that the relationship is two sided. a user can be a buyer or a seller 
    belongs_to :buyer, class_name:"User" 
    belongs_to :seller, class_name:"User" 
end 
+0

貌似'order.buyer'將返回'nil'(而不是返回一個'buyer'實例)。這可能由於多種原因而發生。你確定每個訂單都有與其相關的「買方」嗎? –

+0

是的,他們與桌子有關。這在昨天非常完美。我不知道爲什麼它現在造成一個錯誤! – con

+0

請問您可以發佈「訂單」和「買方」模型的相關部分嗎? –

回答

0

好吧,我猜你需要速戰速決把

<td><%= order.try(&:buyer).try(&:name) %></td> 

這將確保如存在沒有買家不願看到巫婆爲了你沒有得到的錯誤是沒有買家

+0

非常感謝,這解決了問題!也許其中一個出售的項目已連接到我刪除的帳戶? – con

+0

很高興我可以幫助我們都在那裏:) –

0

請問order表有buyer_id的所有記錄嗎?可能有buyer_id爲空的記錄。 或order無法獲得buyer,因爲沒有匹配的ID。