public
Last active

This gist shows how to make a polymorphic association for users in rails which have an specific role, such as Member, Admin...works with devise

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
##Userable
module Userable
def self.included(base)
base.has_one :user, :as => :userable, :dependent => :destroy, :autosave => true
base.validate :user_must_be_valid
base.alias_method_chain :user, :autobuild
base.extend ClassMethods
base.define_user_accessors
end
def user_with_autobuild
user_without_autobuild || build_user
end
def method_missing(meth, *args, &blk)
user.send(meth, *args, &blk)
rescue NoMethodError
super
end
protected
def user_must_be_valid
unless user.valid?
user.errors.each do |attr, message|
errors.add(attr, message)
end
end
end
module ClassMethods
def define_user_accessors
all_attributes = User.columns.map(&:name)
all_attributes << "password"
all_attributes << "password_confirmation"
ignored_attributes = ["created_at", "updated_at", "userable_type", "encrypted_password", "id", "userable_id"]
attributes_to_delegate = all_attributes - ignored_attributes
attributes_to_delegate.each do |attrib|
class_eval <<-RUBY
def #{attrib}
user.#{attrib}
end
def #{attrib}=(value)
self.user.#{attrib} = value
end
def #{attrib}?
self.user.#{attrib}?
end
RUBY
end
end
end
end
 
##Act as user
class ActiveRecord::Base
def self.acts_as_user
include Userable
end
end
 
##User model
belongs_to :userable, polymorphic: true
 
##Polymorphic model
acts_as_user

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.