未定义的方法`max_people”的零:NilClass
问题描述:
我有一个签,提交后,它说: “未定义的方法max_people
为无:NilClass”未定义的方法`max_people”的零:NilClass
checkin.rb:
class Checkin < ApplicationRecord
has_one :payment, dependent: :destroy
has_many :service_items, dependent: :destroy
before_save :calculate_price
belongs_to :user
belongs_to :room
validates :contact_name, presence: true
validates :contact_phone, presence: true, numericality: true, length: {maximum: 11, minimum: 8}
validate :check_num_guest
enum status: [:waiting_pay, :paid, :accept, :reject]
scope :order_desc, ->{order created_at: :desc}
def calculate_price
self.total_price = self.total_price -
self.total_price * self.room.discount/100
end
private
def check_num_guest
if self.num_guest > self.room.max_people
errors.add :checkin, I18n.t("errors.num_people")
end
end
end
checkins_controller.rb:
class CheckinsController < ApplicationController
load_resource :room
def index
@checkins = Checkin.order_desc.paginate page: params[:page]
end
def create
@checkin = Checkin.new checkin_params
@checkin.status = Checkin.statuses[:waiting_pay]
if @checkin.save
@payment = Payment.new
flash[:success] = t "flash.checkins.checkin_success"
render "payments/new"
else
@supports = Support::RoomSupport.new room: @room
flash[:danger] = t "flash.checkins.create_checkin_fail"
render "rooms/show"
end
end
def show
@payment = Payment.new
end
def update
if @checkin.update_attributes checkin_params
flash[:success] = t "flash.checkins.checkin_canceled"
else
flash[:danger] = t "flash.checkins.checkin_cancel_fail"
end
redirect_to checkins_path
end
rescue_from ActiveRecord::RecordNotFound do
flash[:danger] = t "flash.rooms.room_not_found"
redirect_to root_path
end
private
def checkin_params
params.require(:checkin).permit :user_id, :num_guest, :contact_name, :contact_phone, :contact_address, :contact_email, :description, :total_price, :is_cancel, :status, :fromdate, :todate
end
end
表室:
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.string :number
t.boolean :status, default: true
t.float :price
t.string :picture
t.string :description
t.integer :max_people
t.string :facilities
t.datetime :deleted_at
t.integer :discount
t.belongs_to :room_type, foreign_key: true
t.timestamps
end
end
end
答
你check_num_guest
验证尝试拨打房间关系,但你以后不要任何房间分配给签#room
返回nil
。
您必须设置签入的房间。但是,无论如何,如果没有设置空间,我会推荐您将验证转换回来。存在验证器负责未设置的值。
事情是这样的:
def check_num_guest
return unless self.room.present?
if self.num_guest > self.room.max_people
errors.add :checkin, I18n.t("errors.num_people")
end
end
感谢这么much-托比亚斯。我明白了。 – ktanh
@AnhKieu好:)如果你把答案标记为正确的话,会很酷:) – Tobias
我标记了,但系统说了些什么,我不能标记。 :(((。 – ktanh