dimanche 12 février 2017

How can I run validations on a Rails attribute I've overridden?

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:

  1. I can't search for a user by email without an explicit call to to_s.

  2. I can't run a uniqueness validation on the email column anymore. I get a TypeError: can't cast Email to string. (I can fix this with a custom validator.)

Questions:

  1. Is there something wrong with this approach? The fact that it breaks my validation is a code smell to me.
  2. Is there some way to get the existing validates :email, uniqueness: { case_sensitive: false } validation to work with these new accessor definitions?
asked 2 mins ago

Let's block ads! (Why?)



How can I run validations on a Rails attribute I've overridden?

Aucun commentaire:

Enregistrer un commentaire