Вопрос

I am using CanCan on Rails 4 (cancancan) and I want to only authorize the current user from accessing the settings page.

For example user id 1 should only be access /settings/1. User id 1 should not be able to view /settings/2 or any other id.

My roles are: admin, user, guest, banned

Ability.rb:

  include CanCan::Ability

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

Users Controller:

  def settings
    @user = User.find(params[:id])
  end
Это было полезно?

Решение

From the documentation on authorizing controller actions:

# app/controllers/users_controller.rb
def settings
  @user = User.find(params[:id])
  authorize! :settings, @user
end

This assumes that you've properly established your access parameters as such:

# app/models/ability.rb
can :settings, User do |u|
  user.id == u.id
end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top