渡されたパラメータに応じて、Railsアプリケーションでフォームフィールドを検証する方法が2つあります。オブジェクトにparam allow_negative: true
は、私がしたい:ActiveModelフォームが正の値の場合は負の値を持ちますその他の場合は正の値を持つフォーム
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
を10
は、それはちょうどここで、参考のためvalidates :amount
の2番目のインスタンスを実行し、私のクラス全体である:
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