nil的未定义方法`rates':NilClass

时间:2014-04-25 16:09:22

标签: ruby-on-rails ruby

我需要做的是创建一个用户输入姓氏的页面,系统将返回与之相关的信息。我一直收到错误未定义的方法`率'为零:NilClass,我不知道为什么任何帮助将不胜感激。

bookin_controller.rb的代码(@rate_list = r.rates正在抛出错误)

class BookinController < ApplicationController

def bookin


end
  def bookout
  @customer_name = params[:customer_name_in]
   r = Customer.find_by_last(@customer_name)
   @rate_list = r.rates
  end
end

这是rate.rb控制器

class Rate < ActiveRecord::Base


validates :season, :room, :cost, presence: true 

has_many :bookings
  has_many :customers, :through => :bookings

end

2 个答案:

答案 0 :(得分:3)

r = Customer.find_by_last(@customer_name)

返回nil。没有比赛。就是这样。

如果您想在这种情况下安全地应用rates方法,请在nilr时提供nil,然后执行:

@rate_list = r.rates if r

答案 1 :(得分:0)

您没有与该查询匹配的任何记录,因此返回nil

相反尝试这样

def bookout
  @customer_name = params[:customer_name_in]
  @r = Customer.find_by_last(@customer_name)
  @rate_list = @r ? @r.rates : nil
  end

或者您可以将@rate_list = @r ? @r.rates : nil替换为@rate_list = @r.try(:rates)

def bookout
  @customer_name = params[:customer_name_in]
  @r = Customer.find_by_last(@customer_name)
  @rate_list = @r.try(:rates)
end