John Feminella
2014-Apr-26 12:28 UTC
Programmatically copying ActiveModel validators from one model to another?
I'm writing a library that will require programmatically copying
validations from one model to another, but I'm stumped on how to pull this
off.
I have a model that is an `ActiveModel::Model` with some validation:
class User < ActiveRecord::Base
validates :name, presence: true
end
And another model that I'd like to have the same validations:
class UserForm
include ActiveModel::Model
attr_accessor :name
end
Now I'd like to give `UserForm` the same validations as `User`, and without
modifying `User`. Copying the validators over doesn't work, because
`ActiveModel::Validations` hooks into callbacks during the validation check:
UserForm._validators = User._validators
UserForm.new.valid?
# => true # We wanted to see `false` here, but no
validations
# are actually running because the :validate
callback
# is empty.
Unfortunately, there doesn't seem to be an easy way that I can see to
programmatically give one model another's validation callbacks and still
have it work. I think my best bet is if I can ask Rails to regenerate the
validation callbacks based on the validators that are present at a given
moment in time.
Is that possible? If not, is there a better way to do this?
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To view this discussion on the web visit
https://groups.google.com/d/msgid/rubyonrails-talk/2fd13c72-5b16-40d0-a47f-267315a4c2b4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.