How can I pass an object to a string for use with ActiveRecord queries?

I have Userone that has an attribute String email. However, when I do email in my application, I find it advisable to first convert it to an object (not persistent) email, for example:

class User < ActiveRecord::Base
  def email
    Email.new(self.read_attribute :email)
  end
end

Email#to_sand are Email#to_strdefined as just the source string (for example, foo@bar.com), so it is usually pretty transparent to the client regardless of whether they deal with emailor String,

This works great when assigning attributes with ActiveRecord:

> email = Email.new('foo@bar.com')
> user.email = email

ActiveRecord knows that the attribute emailis a string and transforms the object accordingly email. A little puzzling, this is not done when querying the database:

> email = Email.new('foo@bar.com')
> User.find_by email: email
ActiveRecord::StatementInvalid: can't cast Email to string

,

> User.find_by email: email.to_s

?

+4
2

ActiveModel. serialize : Email.

, :

module EmailSupport
  def serialize(value)
    case value
    when Email then value.to_s
    else super
    end
  end
end

ActiveModel::Type::ImmutableString.include(EmailSupport)

User.find_by email: Email.new('foo@example.org')
+4

getter , .

0

Source: https://habr.com/ru/post/1669487/


All Articles