我正在尝试在Rails应用程序中以两种方式之一验证表单字段,具体取决于传入的参数。如果我的对象具有参数allow_negative: true
,我想要:
validates :amount, numericality: {less_than_or_equal_to: 0}
否则我想:
validates :amount, numericality: {greater_than_or_equal_to: 0}
当我尝试这样做时:
validates :amount, numericality: {greater_than_or_equal_to: 0}, unless: :allow_negative
validates :amount, numericality: {less_than_or_equal_to: 0}, if: :allow_negative
它只执行validates :amount
供参考,这是我的全班:
class ViewModel
include ActiveModel::Model
validates :description, presence: true
validates :amount, numericality: {greater_than_or_equal_to: 0}, unless: :allow_negative
validates :amount, numericality: {less_than_or_equal_to: 0}, if: :allow_negative
attr_reader :amount
attr_reader :description
attr_reader :allow_negative
attr_reader :order
def initialize(user, params)
@amount = params[:amount]
@description = params[:description]
@allow_negative = params[:allow_negative]
@order = Order.find(params[:order_id])
end
end
答案 0 :(得分:1)
如果传递了一个实际的布尔值,事实证明上述工作。我传递了一串真或假。一旦我将allow_negative
的值转换为真正的bool,它就会很好用。
答案 1 :(得分:0)
您的代码正在执行的操作是根据:allow_negative
的状态强制执行正值或负值。使用你在那里的结构称它:force_negative
会更准确。
如果您希望:allow_negative
值允许正值和负值,那么您需要这样的内容:
validates :amount, numericality: true
validates :amount, numericality: {greater_than_or_equal_to: 0}, unless: :allow_negative
答案 2 :(得分:0)
您可能需要进行自定义验证,例如:
class ViewModel
include ActiveModel::Model
validates :amount, numericality: true
validate :force_negative
private
def force_negative
if allow_negative && amount > 0
errors.add(:amount, "must be less than or equal to 0")
elsif amount < 0
errors.add(:amount, "must be greater than or equal to 0")
end
end
end