I am using devise and cancan for user authentication and permissions. I need to create a default set of permissions for any NEW user ONLY. I don’t want to mess with devise code so it should be in my user model. What is the best way to do it.
Ok here is what I tried in my model:
before_create :setup_permissions
def setup_permissions
permissions = []
@roles = Role.where('subject_id is null and permissions = ?', 'Read')
@roles.each do |role|
permissions << {:role_id => role.id}
end
self.role_assignments_attributes = permissions
end
But the above code gives an error.
Interestingly I ran code to build permissions from above in console line by line. It produces correct array as shown below.
permissions = [{:role_id=>15}, {:role_id=>17}, {:role_id=>19}, {:role_id=>21}, {:role_id=>23}, {:role_id=>25}, {:role_id=>27}]
And it works when I paste the permissions array directly in the model instead of building it as shown below:
def setup_permissions
permissions = [{:role_id=>15}, {:role_id=>17}, {:role_id=>19}, {:role_id=>21}, {:role_id=>23}, {:role_id=>25}, {:role_id=>27}]
@roles = Role.where('subject_id is null and permissions = ?', 'Read')
@roles.each do |role|
permissions << {:role_id => role.id}
end
self.role_assignments_attributes = permissions
end
I got it to work by adding .to_a at the end of Model.where() to convert it into an array. Rails returns an ActiveRecord::Relationship when you use Model.where() clause instead of Array in case of Model.find(id). This should be corrected and made similar in both cases.