Skip to content

Instantly share code, notes, and snippets.

@denisemauldin
Last active August 29, 2015 13:55
Show Gist options
  • Save denisemauldin/8728027 to your computer and use it in GitHub Desktop.
Save denisemauldin/8728027 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
has_many :study_groups
has_many :studies, :through => :study_groups
has_many :roles, :through => :user_roles
def admin
true if self.roles.include?("admin")
end
def manager
true if self.roles.include?("manager")
end
end
class Role < ActiveRecord::Base
has_many :users, :through => :user_roles
end
class Study < ActiveRecord::Base
has_many :study_groups
has_many :users, :through => :study_groups
end
class StudyGroup < ActiveRecord::Base
belongs_to :study
belongs_to :user
end
class UserRoles < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Ability
def initialize(user)
user ||= User.new
# a user can read studies that they have access to
can :read, Study do |study|
user.study_groups.where(:study_id => study.id)
end
# a manager can only manage the studies they have access to
if user.manager?
can :manage, Study do |study|
user.study_groups.where(:study_id => study.id)
end
end
# an admin can do everything to studies
if user.admin?
can :manage, Study
end
end
end
# user_roles_controller.rb
def create
@user_role = UserRole.new(user_role_params)
if user_role_params[:role_ids].nil? || user_role_params[:role_ids].empty? then
flash[:error] = "No roles selected for creation."
respond_to do |format|
format.html { @user_role = UserRoles.new; render action: "new" }
format.json { render json: @user_role.errors, status: :unprocessable_entity }
end
else
save_status = Array.new
@user_roles = Array.new
user_role_params[:role_ids].each do |role_id|
user_role = UserRoles.create(:user_id => user_role_params[:user_id], :role_id => role_id)
logger.debug("roles user is #{@user_role}.inspect}")
if user_role.save
save_status.push(1)
@user_roles.push(user_role)
else
save_status.push(0)
end
end
failed_save = 0
failed_save = 1 if save_status.include?(0)
end
respond_to do |format|
if failed_save == 1 then
format.html { redirect_to @user_role, notice: 'User role was successfully created.' }
format.json { render json: @user_role, status: :created, location: @user_role }
else
format.html { render action: "new" }
format.json { render json: @user_role.errors, status: :unprocessable_entity }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment