Skip to content

Blogging On Rails

Everything on Rails!

How Do I Authorize Only the Creator of a Post to Update or Delete it?

Let’s say your Rails app has an ActiveRecord data type, Post, and you want to only authorize the creator of that Post, who is of type User, to update or delete the record.

One way to prevent the wrong User from editing the Post is to keep track of the creator with a foreign key, and then ensure that the user editing the object is the creator before you save the changes to the database.

For example, your Post model would have a creator_id column that corresponds to the User that created the post. Then in your Post model, add a belongs_to relationship

class Post < ActiveRecord
  belongs_to :creator, class_name: 'User'
end

Now, anywhere you need to validate the user who is editing the model, use the post’s creator and make sure the editor and the creator are the same:

@post.save if @post.creator == current_user

Now there won’t be any question about who edited that blog post!

Feel free to leave comments or questions below.

Want To Learn More?

Try out some more of my Stimulus.js Tutorials.

Make Interactivity Default 

Make your web app interactive now with easy to implement and simple to add HOTWire integrations. 

Enter your email and get a free sample of my HOTWire Tutorials ebook.

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

Leave a Reply

Your email address will not be published. Required fields are marked *