Created
March 29, 2012 11:56
-
-
Save thechrisoshow/2236521 to your computer and use it in GitHub Desktop.
How to add validations to a specific instance of an active record object?
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 Banana < ActiveRecord::Base; end | |
banana = Banana.new | |
banana.valid? #=> true | |
banana.singleton_class.validates_presence_of :name | |
banana.valid? #=> true - why did the validation not work? | |
banana.class.validates_presence_of :name | |
banana.valid? #=> false - as we'd expect...but now... | |
new_banana = Banana.new | |
new_banana.valid? #=> false - because the previous call soiled the Banana class with it's validation | |
# So how does one apply validations to the eigenclass of an ActiveRecord object? | |
# Or am I misunderstanding what .singleton_class is? |
A method that is directly built into Rails: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validations/with.rb#L115-L123
class Person include ActiveModel::Validations validate :instance_validations, on: :create def instance_validations validates_with MyValidator, MyOtherValidator end end
This solution is not corresponding with the initial subdmision. What the author need is to be able to "inject" as ad-hoc a validator without affecting to the Base class.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A method that is directly built into Rails: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validations/with.rb#L115-L123