Skip to content

Instantly share code, notes, and snippets.

@pedrosmmoreira
Last active December 18, 2015 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrosmmoreira/25051e25473f718838ee to your computer and use it in GitHub Desktop.
Save pedrosmmoreira/25051e25473f718838ee to your computer and use it in GitHub Desktop.
Polymorphic user with Devise
class ApplicationController < ActionController::Base
protect_from_forgery
include Concerns::DeviseRouting
end
class AuthenticableFactory
def self.set_authenticable_for(user)
user.authenticable = build_authenticable_for user
user.authenticable.save
end
def self.build_authenticable_for(user)
user.authenticable_type.constantize.new
end
end
module Concerns
module DeviseRouting
extend ActiveSupport::Concern
included do
helper_method :after_sign_in_path_for
end
def after_sign_in_path_for(user)
user.home_path
end
end
end
class Fan < ActiveRecord::Base
has_one :user, as: :authenticable
def home_path
"/campaigns"
end
end
class Promotor < ActiveRecord::Base
attr_accessible :kind, :name, :website
has_one :user, as: :authenticable
def home_path
"/dashboard"
end
end
ActiveRecord::Schema.define(:version => 20130613163955) do
create_table "fans", :force => true do |t|
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "promotors", :force => true do |t|
t.string "name"
t.string "kind"
t.string "website"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.integer "authenticable_id"
t.string "authenticable_type", :default => "Fan"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
end
class User < ActiveRecord::Base
include Concerns::DeviseStrategies
attr_accessible(
:authenticable_type,
:email,
:password,
:password_confirmation,
:remember_me
)
belongs_to :authenticable, polymorphic: true
delegate :home_path, to: :authenticable
def create
super
AuthenticableFactory.set_authenticable_for self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment