2016-09-16 107 views
-1

我試圖讓用戶一次爲多個空間預訂事件,因此如果一個事件中的一個空間花費£10而用戶想要預訂四個空間,那麼他們需要支付40英鎊。 我已經實現了一個方法,我的預訂模式,以應付這一點 -Rails-如何在數量模型中設置默認值

Booking.rb

class Booking < ActiveRecord::Base 

    belongs_to :event 
    belongs_to :user 

    def reserve 
    # Don't process this booking if it isn't valid 
    return unless valid? 

    # We can always set this, even for free events because their price will be 0. 
    self.total_amount = quantity * event.price_pennies 

    # Free events don't need to do anything special 
    if event.is_free? 
     save 

    # Paid events should charge the customer's card 
    else 
     begin 
     charge = Stripe::Charge.create(amount: total_amount, currency: "gbp", card: @booking.stripe_token, description: "Booking number #{@booking.id}", items: [{quantity: @booking.quantity}]) 
     self.stripe_charge_id = charge.id 
     save 
     rescue Stripe::CardError => e 
     errors.add(:base, e.message) 
     false 
     end 
    end 
    end 
end 

當我嘗試處理預約我碰到下面的錯誤 -

NoMethodError in BookingsController#create 未定義方法`*'爲零:NilClass

這行代碼被突出顯示 -

self.total_amount = quantity * event.price_pennies 

我需要檢查/確保數量返回1或更大的值,並且event.price_pennies返回0(如果它是免費事件)並且如果它是付費事件返回大於0。我該怎麼做呢?

我沒有在我的遷移中爲數量設置任何默認值。我schema.rb文件顯示本作price_pennies -

t.integer "price_pennies",  default: 0,  null: false 

這是什麼在我的控制器創建 -

bookings_controller.rb

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

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

所以,我需要一種方法我的預訂模式,以糾正這一點,或者我應該做一個數量驗證和before_save回調事件?

我不太清楚如何做到這一點,所以任何援助將不勝感激。

回答

0

只投整數,在這種情況下,你似乎做:

self.total_amount = quantity.to_i * event.price_pennies.to_i 
+0

但是,他們已經是整數?這將如何改變事情? –

+0

想要嘗試一下嗎?聽起來像'數量'也可能是'無'。 – mudasobwa

+0

是的,我認爲這是,我如何設置模型中數量的默認值?我在遷移時沒有設置任何內容,它需要爲1或更多。 –

0

遷移來修改你的數據庫結構,而不是數據。

在你的情況下,我認爲你需要爲數據庫添加默認值,爲此你需要使用'db/seeds.rb'文件,每次部署應用程序時調用一次。

當應用程序部署的上面一行代碼執行你會做這樣的事情在seeds.rb

Booking.find_or_create_by_name('my_booking', quantity:1) 

左右。如果表中存在'my_booking',則不會發生任何情況,否則它將創建一個名爲「my_booking」且數量爲1的新記錄。

在您的localhost中,您將執行'rake db:seed'來播種數據庫。

+0

那麼,我可以直接將它放在種子文件中?我需要做耙子db:種子後直? –

+0

對不起,我的意思是在終端命令行。 –

+0

是的,你在命令行上做rake db:seed –