Rails问题 - 未完成的方法'名称'

时间:2017-07-31 17:23:53

标签: html ruby-on-rails ruby

由于某种原因,这个页面不会在rails 5上使用ruby打开它。它为nil提供了一个未定义的方法`name':NilClass错误。

上次打开代码时,代码运行得很完美。有人可以帮忙吗?非常感谢。

这里是视图页面。

<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

3 个答案:

答案 0 :(得分:0)

好的,我想你需要快速修复

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

如果没有买家,这将确保你不会得到错误,而不是没有买家

答案 1 :(得分:0)

order表对所有记录都有buyer_id吗?

也许,有buyer_id为空的记录。 或order无法获取buyer,因为ID不匹配。

答案 2 :(得分:0)

我发现以下链接对了解更多有关&#39;尝试&#39;用法和为什么尝试&#39;在上述情况下,优于救援零选项。

https://rubyinrails.com/2015/08/27/rescue-nil-in-ruby-on-rails