LoginSignup
10
12

More than 5 years have passed since last update.

rails5でDBに保存しないモデルでバリデーションしたい

Posted at

DBに保存しないモデルを定義したいときってありますよね?
そんなときは↓のようにActiveRecord::Base、rails5だとApplicationRecordを継承せずにクラス定義します。

class Book
  attr_accessor :title, :price, :page
end

でも「railsの機能のバリデーションのメソッドを使って、バリデーションを使いたいなー」というとき、どこをincludeすればいいんだろう?ってなりません?

class Book
  attr_accessor :title, :price, :page
  include ActiveRecord::Validations
  include ActiveRecord::Reflection
  validates :title, presence: true
  validates :price, presence: true
  validates :page, presence: true
end

↑のように ActiveRecord::ValidationsActiveRecord::Reflectionincludeするとvalid?が使えるようになります。

book = Book.new
book.price = 567
book.valid?(true)
10
12
1

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
10
12