Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

Best way to grant a user specific permissions

Rails • Asked by Brent C

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. :)

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,242+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.