Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Last active September 15, 2015 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YumaInaura/ecf84dff7c72db139a51 to your computer and use it in GitHub Desktop.
Save YumaInaura/ecf84dff7c72db139a51 to your computer and use it in GitHub Desktop.
Rails: ActiveModel でバリデーションエラーを自分で起こす ( raise ActiveRecord::RecordInvalid ) ref: http://qiita.com/Yinaura/items/24997f0005e187f54210
class Book
include ActiveModel::Model
attr_accessor :title
validates :title, presence: true
def self.new! (params = [])
model = self.new(params)
# invalid? は破壊的メソッド。ここで model にエラー情報が入る。
if model.invalid?
# エラー内容を反映した例外が起こる
raise ActiveRecord::RecordInvalid.new(model)
end
model
end
end
Book.raise_validation_error
Book.new(params)
Book.new.raise_validation_error
Book.new(params)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment