now_world
now_world

Reputation: 1096

rails cancan allow users to edit *only* their data, but view everyones

I have a rails app that uses Devise and cancan. I am wanting to allow only users to edit their own data, but still be able to view everyone elses.

I have:

class Ability
  include CanCan::Ability

  def initialize(user)
  user ||= User.new # guest user (not logged in)

    if user.role == "member"
    their own only
    can :read, User
    can :manage, User, user_id: user.id
  elsif user.role == "guest"

    can :read, User
  end

I also have:

class User < ActiveRecord::Base
  #attr_accessible :name , :email # Include default devise modules. Others available are:

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

ROLES = %w[member guest]


  def is?( requested_role )
    self.role == requested_role.to_s
  end

end

But I can still edit and delete other users comments. When I shouldn't be able to. Why? What am I doing wrong? Rails 4 Devise 2.5.2 cancan 1.6

Thanks

Upvotes: 0

Views: 210

Answers (2)

MarsAtomic
MarsAtomic

Reputation: 10673

You're specifying user_id as a column name for your User model:

can :manage, User, user_id: user.id

I'm willing to bet that User has no user_id column -- it only has an id column. What you want is this:

can :manage, User, id: user.id

Double check this by looking at your schema.rb file and making sure that there is (or is not) a user_id column. The actual ID column is called id and is not listed in schema.rb but is actually present in the database table.

Also, be sure that you really want to allow :manage permissions. The :manage symbol is very powerful and allows the user to do anything with the object in question, including deleting it.

Upvotes: 1

user3506853
user3506853

Reputation: 814

For giving the permission of user to edit their own data, change

From

can :manage, User, user_id: user.id

To

can :update, User

Upvotes: 1

Related Questions