New Discussion

Notifications

You’re not receiving notifications from this thread.

Check a user is author of post before edit or delete

2
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
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.