All threads / Best way to grant a user specific permissions

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

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?

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

I understand it better now, thanks for the video.

Join the discussion

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

Join 37,629+ 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.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.