【问题标题】:Rails skip validation within model with save?Rails跳过模型内的验证并保存?
【发布时间】:2018-04-19 14:31:55
【问题描述】:

我有类似的 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 行,它正在引发错误消息。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

    试试

    .save(validate: false)
    

    【讨论】:

    • 保存!与模型一起出现
    • its, save(valdate: false) 保存一个绕过模型内验证的对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多