Easily Keep Users From Editing Others Posts With Rails And Devise

02 Apr 2013

Devise makes it easy to authenticate users and keep guests from accessing posts.

For example, the following will keep users that aren't signed in from editing, updating, or deleting a post, while still allowing them to view it.

before_filter :authenticate_user!, :only => [:edit, :update, :destroy]

Now a guest will see a login screen upon visiting any of those pages.

Unfortunately, once you log in, you are then able to do all of these things to any post, no matter who the author is.

One option is to use an authentication gem like CanCan which works very well with Devise. If you don't think you need that much functionality and just want to keep posts to themselves, however, simply adding some scope might suffice.

The default update/edit/destroy definitions in the controller will contain something like the following:

@post = Post.find(params[:id])

Simply replace with the following:

@post = current_user.posts.find(params[:id])

Instead of searching through all of the posts, it only searches through the current_user's. If the post is found, then the user will be redirected to the appropriate page. If it isn't, Rails will throw an error (or you can right a conditional to check for it and redirect to your page of choice).