Rails - is it possible to have a shortcut inside the model for its nested attributes?

It might be a stupid question, but it broke my head for a while ...

So I have 2 models: (1) user and (2) profile. The profile is associated with the user through the following relationships:

(1) user has_one :profile
(2) profile belongs_to user

      

This is a standard user and profile dependency on a development system. Anyway, I usually access the username through the following nested attributes:

"user.profile.name"

      

Is it possible to create a "virtual" attribute in a custom model that refers to this attribute in the profile model? I would like to call " user.profile.name

" through " user.name

".

+3


source to share


1 answer


Yes there is: delegate

class User < ...
  delegate :name, to: :profile

   # The rest of your class
end

      



This will drop the method name

from the Profile class to the User class

+3


source







All Articles