Ask A Question

Notifications

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?

Thanks

Reply

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
end

class User
  has_many :posts
end

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
end

class PostUser
  belongs_to :post
  belongs_to :user
end

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

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: "#{@user.name} can now edit the post"
end

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?

Reply

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

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

Reply

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?

Reply

@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. https://gorails.com/episodes/authorization-with-pundit

Reply

I understand it better now, thanks for the video.

Reply
Join the discussion
Create an account Log in

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

Join 87,110+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.