Skip to content

Instantly share code, notes, and snippets.

@danilovelozo
Last active January 17, 2021 12:33
Show Gist options
  • Save danilovelozo/ad1ec977a3b64dd831f3bbd201effbb1 to your computer and use it in GitHub Desktop.
Save danilovelozo/ad1ec977a3b64dd831f3bbd201effbb1 to your computer and use it in GitHub Desktop.
Delegate Pattern With Rails
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: 'velozo.dan@gmail.com', 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 #= "velozo.dan@gmail.com"
profile.username #= "Danilo Velozo"
# app/models/profile.rb
class Profile < ApplicationRecord
belongs_to :user
delegate :username, :email, to: :user, allow_nil: true, prefix: :user
end
# 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