LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】POROにバリデーションを追加する(ActiveModel::Model使用編)

Last updated at Posted at 2019-08-02

環境

  • Rails 5.2.3

やりたいこと

ActiveRecord::Baseを継承していないPORO(Plain Old Ruby Object)に、バリデーションを追加したい。

前提

  • ActiveModel::Modelを利用する(他にもやり方は色々ある)。

バリデーションのトリガー

  • valid?メソッドを実行するとバリデーションが実行される。戻り値はboolean
  • invalid?メソッドでは戻り値がvalid?とは逆になる。

コード例

class Charge
  include ActiveModel::Model

  attr_accessor :amount

  MINIMUM_AMOUNT = 100
  validates :amount, numericality: { greater_than_or_equal_to: MINIMUM_AMOUNT }

  def initialize(amount:)
    @amount = amount
  end
end

実行例

> c = Charge.new(amount: 99)
> c.valid?
=> false
> c.errors.messages
=> {
    :amount => [
        [0] "translation missing: ja.activemodel.errors.models.charge_payment.attributes.amount.greater_than_or_equal_to"
    ]

翻訳エラーは別途要対応。
ここらへんが参考になるはず。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0