繁体   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