'Allow extra parameters with load_and_authorize_resource
I have 3 entities with the following relationships :
a Folder which can have multiple Participants - with firstname and lastname. A participant can be optionally linked to a User which has an email attribute (a user can have multiple participants)
The logic I want to achieve is the following : When creating a Folder, the API should allow to pass a list of participants.
{
"folder": {
"participants_attributes": [
{
"firstname": "Some",
"lastname": "One",
"client_attributes" : {
"email": "[email protected]"
}
},
{
"firstname": "Some",
"lastname": "OneElse"
}
]
}
}
All the participants should be created and attached to the folder.
If a participant has an email attached, we should either create a new user and attach it to the participant or attach the user if it already exists (email has a unique constraint)
Here are my models :
class Folder < ApplicationRecord
has_many :participants
class Participant < ApplicationRecord
belongs_to :user, optional: true
I initially planned to leverage the use of accepts_nested_attributes_for within my Folder and Participant models, and it worked well except for the use an existing user with the same email. I have been told that this logic should be handled at the folder controller level, so I try something like
class FoldersController < ActionController::API
load_and_authorize_resource
def create
participants_attributes = params.extract!(:participants_attributes)
participants_attributes.each |p| do
# the rest of the code processing the logic
...
@folder.save!
render json: @folder
end
def create_params
params.require(:folder).permit(
participants_attributes: [
:firstname,
:lastname,
{ client_attributes: [:email] }
]
)
end
My problem is that the load_and_authorize_resource preload the folder entity with the params, resulting in the following error ActiveModel::UnknownAttributeError (unknown attribute 'participants_attributes' for Folder.)
How can I solve this ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
