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
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!
Comments or Questions? Find me on twitter @jpbeatty
Want To Learn More?
Try out some more of my Stimulus.js Tutorials.