Rails在使用save的模型中跳过验证?

时间:2018-04-19 14:31:56

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 ruby-on-rails-4.2 ruby-on-rails-5.2

我的Rails代码如下:

def charge_card
  return charge_on_house if house_account?
  assign_order_number
  if credit_card?
    begin
      save!   #==>here
      charge = Stripe::Charge.create(
        amount: (total.to_f * 100).ceil,
        currency: 'usd',
        customer: customer.stripe_id,
        card: payment_method,
        description:"Saint Germain Order: #{self.number}"
      )
      self.update(
        payment_status: 'paid'
      )
      self.finish!
    rescue Stripe::StripeError => e
      self.update(
        admin_comments: e.message,
      )
      self.decline!
    ensure
      notify_user
    end
  end
  self.save!
end

我想在保存时跳过验证!在第6行,而不是它提出错误消息。

1 个答案:

答案 0 :(得分:7)

始终运行save!次验证。如果其中任何一个失败ActiveRecord::RecordInvalid就会被提升。

尝试

.save(validate: false)