Last active
January 17, 2021 12:33
-
-
Save danilovelozo/ad1ec977a3b64dd831f3bbd201effbb1 to your computer and use it in GitHub Desktop.
Delegate Pattern With Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rails generate model User first_name:string last_name:string email:string | |
rails generate Profile tagline user:references | |
rails db:migrate | |
User.create({name: 'Danilo Velozo', email: '[email protected]', password: '12345', password_confirmation: '12345'}) | |
Profile.create(tagline: 'My Awesome Profile', user_id: User.first.id) | |
# Or | |
Profile.create(tagline: 'My Awesome Profile', user: User.first) | |
##################################################### | |
# The delegate method allows you to optionally pass allow_nil and a prefix as well. | |
rails c | |
profile = Profile.first | |
profile.email #= "[email protected]" | |
profile.username #= "Danilo Velozo" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/profile.rb | |
class Profile < ApplicationRecord | |
belongs_to :user | |
delegate :username, :email, to: :user, allow_nil: true, prefix: :user | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/user.rb | |
class User < ApplicationRecord | |
has_person_name | |
has_one :profile | |
delegate :username, to: :profile | |
# Include default devise modules. Others available are: | |
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable | |
devise :database_authenticatable, :registerable, | |
:recoverable, :rememberable, :validatable | |
def username | |
"#{first_name}_#{last_name}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment