1
votes

I have the following code:

#/app/models/users/user.rb
class Users::User < ActiveRecord::Base
  has_many :phones, class_name: "Users::Phone"
end

#/app/models/users/phone.rb
class Users::Phone < ActiveRecord::Base
  belongs_to :user, class_name: "Users::User"
  attr_accessible :phone
end


#/app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)

    can :read, :all

    unless user.nil? #logged_in
      if user.is? :admin
        can :manage, :all
      else
        can :create, Users::Phone, user_id: user.id
      end
    end

  end
end

I wanna check ability for create only their own phones for users

#/app/views/users/users/show.html.slim
- if can? :create, Users::Phone.new
  a[href="#{new_user_phone_path(@user)}"] Add phone

Thats does not work, because I should pass user_id to phone model (like Users::Phone.new user_id: user.id), but I can't do that since Phone's mass assignment.

So how I can check :create phones ability for users?

1

1 Answers

5
votes

I do something similar to this in my app by making Ability aware of the underlying parameter structure. You have a few options depending on your requirements. So in your controller you'd have approximately:

def create
  @phone = Users::Phone.new(params[:users_phone])

  # Optional - this just forces the current user to only make phones 
  # for themselves.  If you want to let users make phones for 
  # *certain* others, omit this.
  @phone.user = current_user

  authorize! :create, @phone
  ...
end

then in your ability.rb:

unless user.nil? #logged_in
  if user.is? :admin
    can :manage, :all
  else
    can :create, Users::Phone do |phone|
      # This again forces the user to only make phones for themselves.
      # If you had group-membership logic, it would go here.
      if phone.user == user
        true
      else
        false
      end
    end
  end
end