A while back, there was
discussion on the
engines mailing list on how to add permissions for different roles in the database for the
user engine.
My preferred way of doing this is using migrations. I will illustrate it here using an example, say we have a controller
about with actions
["terms", "privacy", "faq", "about"] and we want to give permissions to both
Guest and
User roles to have access to this.
So, to write a migration for this, fire up a shell and type:
ruby script\generate migration AddPermissionsData
This will create a new migration file in the `db\migrate' folder:
class AddPermissionsData < ActiveRecord::Migration
def self.up
end
def self.down
end
end
Now, to add permissions modify the above file, and add the following code:
class AddPermissionsData < ActiveRecord::Migration
def self.up
guest_role = Role.find_by_name("Guest")
user_role = Role.find_by_name("User")
controller_actions = {:about => ["terms", "privacy",
"faq", "about"] }
controller_actions.each do |controller,actions|
for action in actions
permission = Permission.find_by_controller_and_action(
controller.to_s,action)
if permission
permission.roles << guest_role
permission.roles << user_role
end
end
end
end
def self.down
guest_role = Role.find_by_name("Guest")
user_role = Role.find_by_name("User")
controller_actions = {:about => ["terms", "privacy",
"faq", "about"]}
controller_actions.each do |controller,actions|
for action in actions
permission = Permission.find_by_controller_and_action(
controller.to_s,action)
if permission
permission.roles.delete guest_role
permission.roles.delete user_role
end
end
end
end
end
The code in
self.down should remove whatever was added in
self.up.
Important: Before running the above migration, don't forget to run
rake sync_permissions
.
If you know of a better approach of doing the above then please post it as a comment.