I use CanCan and a Permission
model to manage permissions on a Folder
model.
When a user creates a folder, i want to create a permission to write for this user on the folder (i.e. create a permission record with field action
set to 'write', belonging to both a user and a folder), knowing that this permission might be modified later by an admin (users are not owners of the folders they created). Oddly enough, if a user is admin no permission should be created.
I could use a callback on Folder
to do the job, but i don't think that making current_user
available to the models directly is a good idea.
So here are the options I consider :
- make the dirty job in the controller. I don't like it that much, it's not DRY
- craft a
save_and_grant_permission( user, action )
method onFolder
that would do the job, wrapping the process in a transaction. Problem is i'd have to remember to always use this and not onlysave
So I'd like to know :
- if there are other alternatives
- what would be the best practice in this case
update
For now, i chose solution two and used nested_attributes
:
def save_and_grant_permission( user, action )
return save if user.admin?
permission = permissions.where( user_id: user.id ).first
self.permissions_attributes = [
{id: permission.try(:id), user_id: user.id, action: action.to_s}
]
save
end
If no better solution shows up here, i'll close the question and move it to StackExchange::CodeReview.