Rails 5:添加循环以创建方法并每次加1

时间:2019-02-09 18:48:24

标签: ruby-on-rails

我想在预订中添加order_number。现在每次创建订单时,我都想更改order_number的值。

我尝试过@reservation.order_number = 1000,然后尝试了@reservation.order_number += 1,但是我很快意识到这没有任何意义。

这是我的预订控制器中的创建方法:

def create
    service = Service.find(params[:service_id])

    if current_user.admin?
      flash[:alert] = "Du kannst nicht dein eigenes Angebot kaufen"
    elsif current_user.stripe_id.blank?
      flash[:alert] = "Füge eine Zahlungsmehtode hinzu"
      return redirect_to payment_method_path
    else
      @reservation = current_user.reservations.build
      @reservation.service = service
      @reservation.price = service.price
      @reservation.order_number = 1000

      if @reservation.Bearbeitung!
        flash[:notice] = "Ihre Anfrage wurde erfolgreich versendet"
        ReservationMailer.confirm_email_to_guest(@reservation.user, service).deliver
        confirm_sms(service, @reservation)
      else
        charge(service, @reservation)
      end

    end
    redirect_to submit_reservation_path(@reservation)
  end

1 个答案:

答案 0 :(得分:1)

在模型中,您可以做类似的事情

before_save :add_order_number

private 
  def add_order_number
    default_order_number = 1000
    previous_order = Order.last
      if previous_order
        puts "last order_number was #{previous_order.order_number}"
        self.order_number = previous_order.order_number + 1
      else
        puts  "there was no last number, setting order number to default_order_number"
        self.order_number = default_order_number
      end
  end