2016-09-16 101 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 –