ruby-on-rails Rails:添加到错误[:base]不会使记录无效?

gopyfrb3  于 2023-11-20  发布在  Ruby
关注(0)|答案(4)|浏览(104)

在我的Purchase模型中,我有一个计算税的方法:

def calculate_tax
  if self.shipping_address.state == State.new_york
    corresponding_tax = Tax.find_by(zip_code: self.shipping_address.zip_code, state_id: self.shipping_address.state_id)
    if corresponding_tax
      self.tax = corresponding_tax.rate * (self.subtotal + shipping)
    else
      #HERE !!!
      self.errors[:base] << "The zip code you have entered is invalid."
      puts "errors = #{self.errors.full_messages}" #<-- this prints out the error in my log, so I know it's being run
    end
  else
    self.tax = 0.00
  end
end

字符串
在此方法中调用此方法:

def update_all_fees!
  calculate_subtotal
  calculate_shipping
  calculate_tax #<-- being called here
  calculate_total
  save!
end


然而,save!成功保存了记录。它不应该抛出异常吗?当calculate_tax在第二个else块中时,我如何使保存!失败?

nsc4cvqm

nsc4cvqm1#

您可以使用validate指令添加自定义验证方法。以下可能采用您发布的代码:

class Purchase < ActiveRecord::Base
  validate :new_york_needs_tax_record

  def update_all_fees!
    calculate_subtotal
    calculate_shipping
    calculate_tax
    calculate_total
    save!
  end

  private

  def calculate_tax
    if ships_to_new_york? && corresponding_tax
      self.tax = corresponding_tax.rate * (self.subtotal + shipping)
    elsif !ships_to_new_york?
      self.tax = 0.00
    else
      self.tax = nil
    end
  end

  def ships_to_new_york?
    self.shipping_address.state == State.new_york
  end

  def corresponding_tax
    Tax.find_by(zip_code: self.shipping_address.zip_code, state_id: self.shipping_address.state_id)
  end

  def new_york_need_tax_record
    if ships_to_new_york?  && !corresponding_tax
      self.errors[:base] << "The zip code you have entered is invalid."
    end
  end
end

字符串

rqdpfwrv

rqdpfwrv2#

出于历史原因编辑的。第一次回应没有涵盖所有情况。
但如果你需要提出的错误,如果有任何只是做:

validate :taxes_scenario

def taxes_scenario
  [Add any clause here that makes your scenario invalid]
end

字符串
因此,您可以验证税收方案,并确保正确添加错误。

gdrx4gfi

gdrx4gfi3#

简单地在错误列表中添加一个错误不会使记录失败。你必须设置一个所谓的“验证”。有一些关于它的精彩指南here应该可以帮助你完成这个过程。
例如,在本例中,您可能希望向税务模型添加以下验证:
第一个月
一旦设置了验证,当模型验证失败时,save!应该自动输出错误

au9on6nz

au9on6nz4#

在Rails 7中:

class User < ApplicationRecord

  validate :must_be_a_friend

  def must_be_a_friend
    if friend == false
      # Does NOT work anymore
      errors[:base] << 'Must be friends'
    
      # DOES work
      errors.add(:base, 'Must be friends', strict: true)
    end
  end
  
end

字符串

相关问题