Vote count: 0
I have a User
model with an email
attribute. Various parts of my app conceive of an "email" differently; sometimes as a string, sometimes as a hash ({ token: 'foo', host: 'bar.com' }
), sometimes as an object. This is bad; I want the concept of an email to be consistent wherever I use it.
So, I use an Email
object that does what I want. I don't see any good reason to create an Email
table; instead, I just want to create a new Email
object corresponding to an email string whenever I need one. Therefore User
looks like this:
class User < ActiveRecord::Base
def email
Email.new(read_attribute :email)
end
def email= email
write_attribute :email, email.to_s
end
end
However, this causes at least two issues:
-
I can't search for a user by email without an explicit call to
to_s
. -
I can't run a uniqueness validation on the
email
column anymore. I get aTypeError: can't cast Email to string
. (I can fix this with a custom validator.)
Questions:
- Is there something wrong with this approach? The fact that it breaks my validation is a code smell to me.
- Is there some way to get the existing
validates :email, uniqueness: { case_sensitive: false }
validation to work with these new accessor definitions?
How can I run validations on a Rails attribute I've overridden?
Aucun commentaire:
Enregistrer un commentaire