2016-07-27 40 views
0

我真的在我的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 

錯誤彈出,當我試圖完成測試預訂。

+0

你可以更新你的問題與所有的代碼'create'方法和任何私人方法你在這個方法中使用? –

+0

剛剛更新。 –

+0

你能用測試代碼更新你的問題嗎? –

回答

0

的問題是這樣的:

@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 
+0

嗨,已經將上述方法引入我的模型中,現在我得到以下錯誤'無法強制插入Fixnum'。我怎樣才能解決這個問題? –

+0

錯誤在同一行嗎?我會檢查以確保您的預訂中沒有一個沒有數量(也許沒有您的事件具有零個number_of_spaces)。如果這是問題,請確保您在模型中對這些字段進行驗證。 – australis

相關問題