2017-07-31 62 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。

相关问题