I have the snippet below in my ability.rb
file:
def initialize(user)
if user.group === 1
can :manage, Task do |task|
task.user.id === user.id
end
end
end
The user has_many
tasks and each task belongs_to
a user. The task record being requested (7) has a user_id
of 4. The user sending the request has a user_id
of 4.
In the tasks show method, I have this snippet to authorize and return the data:
def show
@task = Task.find(params[:id])
authorize! :read, @current_user
render json: @task, root: "task"
end
Why would it be denied?
You need to authorize the task, not the current_user. The current_user is assumed:
def show
@task = Task.find(params[:id])
authorize! :read, @task
render json: @task, root: "task"
end
In your abilities file you could write it like this:
def initialize(user)
can :manage, Task do |task|
task.user.id == user.id && user.group == 1
end
end