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 :
save_and_grant_permission( user, action )
method on Folder
that would do the job, wrapping the process in a transaction. Problem is i'd have to remember to always use this and not only save
So I'd like to know :
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.
Perhaps you should give your folder a reference to a user in the form of an author.
You can base your permissions on the author of the folder and for example define an after_create callback that creates a permission for the folder's author.