Skip to main content

Check a user is author of post before edit or delete

Rails • Asked by Philip Benton

Hi all,

What is the best way to check a user (current_user) owns a post before edit or delete?

I have a Post model with a has_one relationship to the User model, user_id is set. The logged in user is stored within current_user.

Is it as simple as writing a method such as:

def is_author?
    redirect_to root_path unless @post.user == current_user
end

and using a before_action:

before_action :is_author?, only: [:edit, :update, :destroy]

Hey Philip,

Yes, that's fine to do.

I personally prefer to just check by @post.user_id as opposed to @post.user as it will most likely have to hit the DB to fetch the user object, whereas @post.user_id == current_user.id won't need to.


Thanks Jacob, that makes more sense.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.