How would you prevent other users from editing a object, say a profile object that does – not – belong to themselves?
Most online examples are complexes with multiple user roles, i haven’t been able to get this working, must be simple though:
def initialize(user)
can :update, Profile do |profile|
profile.try(:user) == current_user
end
end
And inside my ProfilesController#edit
authorize! :update, @profile
First question is, have you made your roles for the
User?app/models/user.rb
As you can see I have 3 different roles here and when a new user is created they are always
defaultusers. Now with CanCan set up, lets say you wanted to have theadminbe able to do everything, thedefaultusers be able to do everything with their own profiles,bannedusers cannot do anything and guest users be able to see profiles:So that’s how you let users edit only their own profiles and nobody elses.
Some other handy notes: Make sure you have a
user_idcolumn in yourProfiletable. Also if you may need to let guess users see profiles like this:They won’t be able to use any other action and CanCan still checks authentication on everything else except
show.Good luck!
UPDATE: Making :role attribute for Users
What I did was run a migration that would add the
rolecolumn to the Deviseuserstable:And then
rake db:migrate. The new migration file should look like this and also check your db/schema.rb file to make sure its apart of the users table correctly. If it isn’t thenrake db:drop, thenrake db:createand thenrake db:migrateagain.This is how you successfully make the
user.rolework.Note: Make sure you leave the line:
can :manage, Profile, :user_id => user.idas is with no changes. It should work after adding therolecolumn touser.IMPORTANT! If you use Rails 3, DO NOT MAKE
roleattr_accessibleor everyone can edit their roles! Rails 4 uses Strong Parameters by default and is not affected by this issue as you can choose the allowed parameters.