Rails名称错误 - 未定义的局部变量或方法`booking'

时间:2017-02-03 11:56:30

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller

我正在Rails中构建一个Events应用程序,我在上面的错误中遇到了与我的模型中此方法相关的错误 -

    def validate_availability
        errors.add(:base, 'event is fully booked') if booking.count >= event.number_of_spaces
    end

该方法的目的是避免过度预订可获得特定数量空间的事件。在我的控制器中,我有以下代码 -

控制器#创建

 def create

    @event = Event.find(params[:event_id])
    @booking = @event.bookings.new(booking_params)
    @booking.user = current_user

        if 
            @booking.set_booking
            flash[:success] = "Your place on our event has been booked"
            redirect_to event_booking_path(@event, @booking)
        else
            flash[:error] = "Booking unsuccessful"
            render "new"
        end

        if @event.is_free?
            @booking.save(booking_params)
        end

        if booking.count >= @event.number_of_spaces
            flash[:error] = "Sorry, this event is now fully booked"
            render "new"
        end
end

我需要在我的控制器中定义booking.count但不确定什么会起作用 - 尝试了一些事情,但没有工作。我的架构中有以下内容 -

   create_table "bookings", force: :cascade do |t|
    t.integer  "event_id"
    t.integer  "user_id"
    t.string   "stripe_token"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.integer  "quantity",         default: 1
    t.integer  "total_amount"
    t.string   "stripe_charge_id"
    t.string   "booking_number"
  end

booking.count将依赖于用户希望的空间/预订数量与剩余空间的数量,但我该如何表达?我是否需要在表格中使用total_bookings列或单独的方法?

更新 -

Booking.rb

class Booking < ActiveRecord::Base

  belongs_to :event
  belongs_to :user
  before_create :set_booking_number


  validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0 }
  validates :total_amount, presence: true, numericality: { greater_than_or_equal_to: 0 }

  validate(:validate_booking)
  validate(:validate_availability)

  def set_booking_number
    self.booking_number = "MAMA" + '- ' + SecureRandom.hex(4).upcase
  end

  def set_booking

        if self.event.is_free?
          self.total_amount = 0
          save!
        else
          self.total_amount = event.price_pennies * self.quantity
          begin
            charge = Stripe::Charge.create(
              amount: total_amount,
              currency: "gbp",
              source: stripe_token, 
              description: "Booking created for amount #{total_amount}")
            self.stripe_charge_id = charge.id
            save!
          rescue Stripe::CardError => e
            # if this fails stripe_charge_id will be null, but in case of update we just set it to nil again
            self.stripe_charge_id = nil
            # we check in validatition if nil

          end

        end


  end

      def validate_booking

        # stripe_charge_id must be set for not free events
        unless self.event.is_free?
          return !self.stripe_charge_id.nil?
        end
      end

      private 

        def validate_availability
            errors.add(:base, 'event is fully booked') if event.bookings.count >= event.number_of_spaces
        end

end

1 个答案:

答案 0 :(得分:0)

对于预订表的计数,您应该在事件表中有一个booking_count字段。为此使用计数器缓存。有关详情,请查看http://guides.rubyonrails.org/association_basics.html。当记录很大时,这非常有用。

您添加列的迁移应与以下内容类似:

def change
    add_column :events, :bookings_count, :integer, default: 0
    Event.reset_column_information
    Event.all.each do |e|
      Event.update_counters e.id, :bookings_count => e.bookings.length
    end
  end