Last active
September 15, 2015 09:14
-
-
Save YumaInaura/ecf84dff7c72db139a51 to your computer and use it in GitHub Desktop.
Rails: ActiveModel でバリデーションエラーを自分で起こす ( raise ActiveRecord::RecordInvalid ) ref: http://qiita.com/Yinaura/items/24997f0005e187f54210
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Book.raise_validation_error |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Book.new(params) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Book.new.raise_validation_error |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Book.new(params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment