Created
October 7, 2010 17:32
-
-
Save sterrym/615493 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class CreateRoles < ActiveRecord::Migration | |
def self.up | |
create_table :roles do |t| | |
t.string :name | |
t.string :role | |
t.timestamps | |
end | |
create_table :user_roles do |t| | |
t.references :user | |
t.references :role | |
t.timestamps | |
end | |
add_index :user_roles, [:user_id, :role_id], :unique => true | |
end | |
def self.down | |
drop_table :user_roles | |
drop_table :roles | |
end | |
end |
This file contains hidden or 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
class Role < ActiveRecord::Base | |
validates_presence_of :name, :role | |
has_many :users, :through => :user_roles | |
has_many :user_roles | |
class << self | |
def roles | |
all.map{|r| r.role.to_sym} | |
end | |
end | |
end |
This file contains hidden or 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
class User < ActiveRecord::Base | |
has_many :roles, :through => :user_roles | |
has_many :user_roles, :dependent => :destroy | |
def assign_role(role_name) | |
unless self.role?(role_name) | |
role = Role.find_by_role(role_name.to_s) | |
role ||= Role.find_by_name(role_name.to_s) | |
raise ActiveRecord::RecordNotFound unless role | |
self.roles << role if role | |
self.roles | |
end | |
end | |
def role?(role) | |
!!self.roles.find_by_role(role.to_s) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment