簡體   English   中英

Rails-BookingsController#中的ArgumentError創建錯誤的參數數量(給定1,預期2..3)

[英]Rails - ArgumentError in BookingsController#create wrong number of arguments (given 1, expected 2..3)

我在Rails應用程序中確實遇到上述錯誤。 它突出顯示了Bookings Controller,尤其是“ create”操作的這一部分-

if ( @event.bookings.sum(&:quantity) + @booking.quantity ) > @event.number_of_spaces
        flash[:warning] = "Sorry, this event is fully booked."
        redirect_to event_path(@event)
    end

這是完整的控制器代碼-

bookings_controller.rb

class BookingsController < ApplicationController

before_action :authenticate_user!

def new
    # booking form
    # I need to find the event that we're making a booking on
    @event = Event.find(params[:event_id])
    # and because the event "has_many :bookings"
    @booking = @event.bookings.new
    # which person is booking the event?
    @booking.user = current_user
    @booking.quantity = @booking.quantity
    @total_amount = @booking_quantity.to_f * @event_price.to_f

end

def create
        # actually process the booking
        @event = Event.find(params[:event_id])
        @booking = @event.bookings.new(booking_params)
        @booking.user = current_user
        #@total_amount = @booking.quantity.to_f * @event.price.to_f

    if ( @event.bookings.sum(&:quantity) + @booking.quantity ) > @event.number_of_spaces
        flash[:warning] = "Sorry, this event is fully booked."
        redirect_to event_path(@event)
    end

    if @booking.save
        if @event.is_free?
        flash[:success] = "Your place on our event has been booked"
        redirect_to event_path(@event)
    else
        begin
            # CHARGE THE USER WHO'S BOOKED
            Stripe::Charge.create(
                amount: @event.price_pennies,
                currency: "gbp",
                source: @booking.stripe_token,
                description: "Booking number #{@booking.id}"
            )

            flash[:success] = "Your place on our event has been booked"
            redirect_to event_path(@event)
        rescue => e
            @booking.destroy  # delete the entry we have just created
            flash[:error] = "Payment unsuccessful"
            render "new"
        end
     end
  end
end


private

def booking_params
    params.require(:booking).permit(:stripe_token, :quantity)
end



end

當我嘗試完成測試預約時,會彈出錯誤消息。

問題是這樣的:

@event.bookings.sum(&:quantity)

我想您正在嘗試確定特定事件的預訂總數?

一個很好的方法是:

@event.bookings.reduce(0) { |i, b| i + b.quantity }

當然,這應該是事件模型中的方法,而不是控制器中的方法:

class Event < ActiveRecord::Base

  ...

  def total_bookings
    self.bookings.reduce(0) { |i, b| i + b.quantity }
  end
end

然后控制器中的線變為

if ( @event.total_bookings + @booking.quantity ) > @event.number_of_spaces

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM