简体   繁体   中英

Rails Permissions: CanCanCan Abilities- Show only what user creates

I'm working on my abilities model on my Rails app to define my user authorization/abilities using cancancan. At the moment, here's what my ability.rb file looks like this:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
        if user.admin?
            can :manage, :all
        else
            can :manage, Application
            can :read, User
        end
    end
 end

I'm testing my app now. when I log into an account that doesn't have the admin boolean and go to to say /users, they can access that page, but clicking the show buttons or anything else leads them to the root page and says that they don't have permission. Currently I have an Applications controller/model (poor naming convention, realized later). But I simply wanted to make it so that any user who has a boolean FALSE for if they're admin has different abilities. I want the admin? true person to be able to do anything, but I want everyone else to be only able to SEE THEIR OWN own application (not everything entered by all users), only be able to create one application, and only be able to see their own information on the user show page, and only be able to edit their own user information. Can anyone explain how to specify for the things only the users create and such? Thank you!

define role column into your database and insert following line into your model

generate migration:

class AddRoleToUser < ActiveRecord::Migration
  def change
      add_column :users, :role, :integer
  end
end

insert this into your model like (User.rb)

  enum role: [:Admin, :Client, :Enduser, :ClientUser, :Moderator]

then you can manage your permission using cancancan

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
        if user.admin?
            can :manage, :all
        else
           can [:new,:create, :update, :destroy], User
        end
    end
 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM