Skip to content

Commit ed1be1b

Browse files
committed
Don't load resource via CanCanCan in Api::ProjectsController
As I explained in the previous commit, the `load_project` before action is where we want the project to be loaded, i.e. via `ProjectLoader` so that it's found by a combination of `Project#identifier` and `Project#locale`. To make this clearer, I've changed the `load_and_authorize_resource` before action to `authorize_resource` [1], so the CanCanCan authorization uses the project found by the `load_project` before action. However, this meant that if the project was *not* found by the `load_project` before action an exception was raised in `Project::Update.call` resulting in a 422 Unprocessable Entity response with the following error message: Error persisting changes: undefined method `components' for nil:NilClass To fix this I'm now raising an `ActiveRecord::RecordNotFound` exception in the `load_project` before action if no project is found. This results in the expected 404 Not Found response. I think there's a strong case to be made the this exception raising behaviour should be added to `ProjectLoader#load`. However, that's a bigger change with a lot more risk, so I'm going to leave that for now. Note that I've retained the load resource functionality for the `create` action, because the `load_project` before action isn't triggered for `create` and the authorize resource functionality seems to rely on the project built by the load resource step and I want to keep changes to a minimum. [1]: https://github.com/CanCanCommunity/cancancan/blob/3.4.0/docs/controller_helpers.md#authorize_resource-load_resource-load_and_authorize_resource
1 parent 27bd1bd commit ed1be1b

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

app/controllers/api/projects_controller.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ class ProjectsController < ApiController
77
before_action :authorize_user, only: %i[create update index destroy]
88
before_action :load_project, only: %i[show update destroy show_context]
99
before_action :load_projects, only: %i[index]
10-
load_and_authorize_resource
10+
load_resource only: :create
11+
authorize_resource
1112
before_action :verify_lesson_belongs_to_school, only: :create
1213
after_action :pagination_link_header, only: %i[index]
1314

@@ -73,6 +74,7 @@ def load_project
7374
else
7475
project_loader.load
7576
end
77+
raise ActiveRecord::RecordNotFound if @project.blank?
7678
end
7779

7880
def load_projects

0 commit comments

Comments
 (0)