Example:
User A (id=10) has created a photo resource
photo: (id: 1 user_id = 10, url: "http://...")
Now, if User B (id=20) go to this url: /photos/1/edit
it can edit photo of user A!!!
Rails+Devise provides something for this by default? It seems it's a very common issue
I just need to allow that any user can edit/delete ONLY resource it has created (where current_user == resource.user)
Using: Rails 4, Devise
Update:
I think CanCan it's something too advanced. I don't need roles or restrict some actions to certain users
Write another before_filter in application_controller:
And you can use it in views, not to show users link they can't follow.
Some kind of this, of course you need to modify it to suit your needs.
So you are using
gem devise
.This gem provides the
current_user
for the currently logged in user.In your
PhotosController#edit
method. I'd do something like below.This method is cheaper because you already have 2 objects to compare instead of running a query in the comparison.
You can make use of Rails' associations and write it like this:
This will only find a record when the photo with the supplied ID belongs to the current user. If it doesn't, Rails will raise a
ActiveRecord::RecordNotFound
exception.Of course, I'm assuming the
current_user
method is available and yourUser
model contains the statementhas_many :photos
.