Created — forked from sj26/gist:2310315

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View gist:2318574
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
class User < ActiveRecord::Base
attr_accessible :name
 
has_many :admin_memberships, class_name: "Membership", conditions: {role: 'admin'}
has_many :editor_memberships, class_name: "Membership", conditions: {role: 'editor'}
 
def admin?
admin_memberships.exists?
end
 
def editor?
editor_memberships.exists?
end
end
 
class Group < ActiveRecord::Base
attr_accessible :name
 
has_many :admin_memberships, class_name: "Membership", conditions: {role: "admin"}
has_many :editor_memberships, class_name: "Membership", conditions: {role: "editor"}
has_many :admins, through: :admin_memberships, source: :user
has_many :editors, through: :editor_memberships, source: :user
end
 
class Membership < ActiveRecord::Base
attr_accessible :role
 
belongs_to :user
belongs_to :group
end
 
sam = User.new name: "Sam"
# => #<User id: 1, name: "Sam", created_at: "2012-04-05 11:45:54", updated_at: "2012-04-05 11:45:54">
rainbows = Group.new name: "Rainbows"
# => #<Group id: 1, name: "Rainbows", created_at: "2012-04-05 11:46:06", updated_at: "2012-04-05 11:46:06">
rainbows.admins << sam
# => [#<User id: 1, name: "Sam", created_at: "2012-04-05 11:45:54", updated_at: "2012-04-05 11:45:54">]
rainbows.admin_memberships
# => [#<Membership id: 2, user_id: 1, group_id: 1, role: "admin", created_at: "2012-04-05 11:48:58", updated_at: "2012-04-05 11:48:58">]
user.admin?
# Membership Exists (0.3ms) SELECT 1 FROM "memberships" WHERE "memberships"."user_id" = 1 AND "memberships"."role" = 'admin' LIMIT 1
# => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.