All threads / Best way to grant a user specific permissions
Ask A Question


You’re not receiving notifications from this thread.

Best way to grant a user specific permissions

Brent C asked in Rails

Trying to determine which way I should handle this.

Normal User adds a post to our system, he then has the ability to update and delete this post. In the future he may assign other users the ability to edit, delete, update etc.

Should I create a has_many / belongs_to relationship between the user and post or should I handle this through roles via CanCanCan? Or both?


Since that user can add access to other users specific to that post, you'll probably want to create a join table between the two and then use CanCanCan to verify if they are the owner or an editor.

Right now you probably have this:

class Post
  belongs_to :user

class User
  has_many :posts

And if you refactor so that the users are stored in a join table, you can have multiple users with access to a post:

class Post
  has_many :post_users
  has_many :users, through: :post_users

class PostUser
  belongs_to :post
  belongs_to :user

class User
  has_many :post_users
  has_many :posts, through: :post_users

When you create a post, you'll want to add @post.users << current_user so that the person who created the post is in the users list.
You can add another action to give access to another user which just accepts a user_id and does something like the following:

def add_user
  @user = User.find(params[:user_id])
  @post.users << @user
  redirect_to @post, notice: "#{} can now edit the post"

Then you can simply use CanCanCan to check if the user is in the users array for a post. If they are they can manage the post; if they aren't they can't manage the post.

Does that make sense for what you want?

Absolutely, this is exactly what I was trying to wrap my head around.

Thanks a ton Chris for the clear and straight forward explanation. :)

Hello Chris,

I am having this exact issue now, I don't know how to set the form that will allow users to add other users to edit their posts and also how to define my ability in cancancan gem.

Can you help out please?

@oomis, take a look at the Pundit episode. Since I wrote this, I've used the Pundit gem for authorization over CanCanCan. It's less confusing to me.

I understand it better now, thanks for the video.

Join the discussion

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

Join 69,840+ 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.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.