0

我正在使用Ruby On Rails构建事件应用程序。我正拼命想找到一种方法来处理多个用户的预订 - 所以他们可以选择预订多个空间(目前他们只能预订一个空间),并且该应用会将该数字转换为正确的价格(每票10英镑的10张门票费用为100英镑等)。 随着SO &谷歌,我已经看了许多方法在我bookings.rb模型使用帮助,这是最新的 -Ruby - 如何在字符串中提取£符号以进行浮点型转换

def total_amount 
    quantity.to_i * strip_currency(event.price) 
end 

private 

    def strip_currency(amount = '') 
     amount.to_s.gsub(/[^\d\.]/, '').to_f 
    end 

我也试了这一点 -

def total_amount 
     self.quantity.to_i * self.event.price.to_f 
    end 

当我点击支付页面时,两种方法都返回0(零)。它基本上归结为£符号(或者我错过了其他东西?)。它已经表明,这个等式可能工作 -

string[0..-1].to_f 

不过,我很新的这一点,不知道如何或在哪里我想这个融入我的MVC的代码,以便为它工作。我没有使用获利宝石,我正在使用money-rails,但必须有一个简单的代码方式/线路才能让此方法起作用。

这里是我的booking_controller -

class BookingsController < ApplicationController 

    before_action :authenticate_user! 

    def new 
    @event = Event.find(params[:event_id]) 
    @booking = @event.bookings.new(quantity: params[:quantity]) 
    @booking.user = current_user 
    end 

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

    Booking.transaction do 
     @event.reload 
     if @event.bookings.count > @event.number_of_spaces 
     flash[:warning] = "Sorry, this event is fully booked." 
     raise ActiveRecord::Rollback, "event is fully booked" 
     end 
    end 

    if @booking.save 
     # CHARGE THE USER WHO'S BOOKED 
     # #{} == puts a variable into a string 
     Stripe::Charge.create(
     amount: @event.price_pennies, 
     currency: "gbp", 
     card: @booking.stripe_token, 
     description: "Booking number #{@booking.id}") 
     flash[:success] = "Your place on our event has been booked" 
     redirect_to event_path(@event) 
    else 
     flash[:error] = "Payment unsuccessful" 
     render "new" 
    end 

    if @event.is_free? 

     @booking.save! 
     flash[:success] = "Your place on our event has been booked" 
     redirect_to event_path(@event) 
    end 
    end 

    private 

    def booking_params 
     params.require(:booking).permit(:stripe_token, :quantity) 
    end 
end 

上午我找错了树和Ruby - 我应该使用JavaScript的呢?

+0

正确的价值观的代码我不确定你在哪里找回价格。如果你必须把它作为一个字符串存储,我会改变'Event#price'返回一个浮点数。或者更好的是,我会在存储价格并将价格存储为浮动之前直接剥离货币。 – Andrea

+0

这就是我正在尝试使用上面发布的第一种方法。我显然做错了,因为它不工作 - 你会怎么做? –

回答

1

你已经和预期一样

调试和检查什么值你正在为quantityevent.price

amount = '£10' 
quantity = 2 

strip_currency(amount) 
#=> 10.0 

quantity.to_i * strip_currency(amount) 
#=> 20.0 

也许你没有得到在任何数量或数量

+0

你是什么意思?我如何检查这个? –

+0

@ Mike.Whitehead为了测试这个,我打开了一个ruby的交互式控制台。我把你的代码和输入由Deepak提供的步骤。它确实有效。 –

+1

在该方法中应用调试器或binding.pry,也许你没有得到你所期望的值 –