All threads / Check a user is author of post before edit or delete

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]

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.

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.