Ruby - 如何在方法

时间:2016-08-10 20:15:27

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller methods

我使用一种方法尝试将两个变量相乘,如下所示 -

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

我正在使用Ruby on Rails构建一个事件应用程序,该方法的目的是允许一个用户为付费事件预订多个空间。

该方法根本不起作用,因为当我点击进行付款时,金额只显示为0(零)。该方法在我的预订模型中,在我的预订控制器中,我有以下代码 -

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

我在events.show表单上有一个输入空间,允许用户输入所需的空格数。预订表格中包含以下代码,这些代码应反映所需的总金额 -

<p>Total Amount<%= @booking.total_amount %></p>

我向两个变量添加了.to_i,因为没有这个我收到了NilClass错误。如何修改此方法以便方法创建正确的输出?

2 个答案:

答案 0 :(得分:0)

您可以使用正则表达式去除货币符号

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

private

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

答案 1 :(得分:-2)

如果您正在调用booking.new,则表示您正在创建类的实例,其中self.表示您正在使用类变量。

删除self