You’re not receiving notifications from this thread.
Check a user is author of post before edit or delete
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]
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.