I have the following class:
class ArticlesController < ApplicationController
def create
article = Article.new(article_params)
end
private
def article_params
params.permit(:name, :age, book: [])
end
end
and I have a field called book that contains a collection followed by a hash [{...}], inside the hash object it can contain any random attribute, for example:
book_1 =
[
{
"id": "a1",
"type": "Color",
"title": "Live life cicle",
"content": "image_intro.png"
},
]
book_2 =
[
{
"id": "a2",
"email": "[email protected]",
"domain": "http://ddd.com"
}
]
...
book_7
[
{
"id": "a23",
"width": "3px",
"heigth": "5px",
"exist": true
}
]
What I would like is that every time I save a book, it can go through article_params no matter what attributes it contains within the hash, if you could help me please I would be grateful.
ActionController::Parameters does not have a "wildcard" syntax to allow any nested hash keys. But it does have #permit!
which is an acknowledgement that strong parameters is not the solution for every possible problem.
permit!
completely circumvents whitelisting by setting the permitted
attribute on the ActionController::Parameters instance.
It will also set the permitted attribute on any nested instances of ActionController::Parameters - ie nested hashes in the parameters.
This is a very sharp tool which should be used with care.
In this case you might want to just use it on the nested attributes:
params.permit(:name, :age).merge(
books: params.dup.permit!.fetch(:books, [])
)