Rails - BookingsController中的ArgumentError#创建错误数量的参数(给定1,预期2..3)
我真的在我的Rails应用上苦于上述错误。它突出了登记控制器,特别是“创造”的行动,这部分 -Rails - BookingsController中的ArgumentError#创建错误数量的参数(给定1,预期2..3)
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
嗨,已经将上述方法引入我的模型中,现在我得到以下错误'无法强制插入Fixnum'。我怎样才能解决这个问题? –
错误在同一行吗?我会检查以确保您的预订中没有一个没有数量(也许没有您的事件具有零个number_of_spaces)。如果这是问题,请确保您在模型中对这些字段进行验证。 – australis
你可以更新你的问题与所有的代码'create'方法和任何私人方法你在这个方法中使用? –
刚刚更新。 –
你能用测试代码更新你的问题吗? –