Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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.