Ask A Question

Notifications

You’re not receiving notifications from this thread.

Check a user is author of post before edit or delete

Philip Benton asked in Rails

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]
Reply

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.

Reply

Thanks Jacob, that makes more sense.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 78,890+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.