I have a form that I'm creating with an ENORMOUS list of questions. Rather than hard-code all these out in html.
I'm planning on storing them in a table called questions
and populating a questionnaire view by looping through the table with a script that pulls both the text of the question from one column, and its corresponding parameter from another.
The answers will be stored in a Questionnaire
model and table. This seems relatively straight-forward, except when dealing with strong params.
So I have the model Question
, and table questions
. Which contains the columns the_questions
and the_parameters
.
The questions contained in that table correspond to fields for the model Questionnaire
. I would like to query the database to get an array of the parameters and then drop them into the strong params in the questionnaire controller.
So rather than:
def questionnaire_params
params.require(:questionnaire).permit(:an, :enormous, :list, :of, :params.....)
end
I'd like to do something like:
def questionnaire_params
@my_params=Questions.the_parameters
params.require(:questionnaire).permit(@my_params)
end
Is there any way to do this? Am I way out in left field with this idea? Any guidance or admonishment would be appreciated.
I would like to query the database to get an array of the parameters and then drop them into the strong params in the questionnaire controller.
This would mean, you'll permit all and each attribute to be massassigned.
To do so you just need to use permit!
method, which will whitelist every model's attribute:
params.require(:questionnaire).permit! # I don't want to even start discussing downsides of whitelisting all attributes
If you though have some attributes, you don't want to allow to be mass assigned and still want to use array, you can define
def questionnaire_params
@all_attributes = Model.column_names.map(&:to_sym)
@not_permitted = [:id, :some_other_attribute]
params.require(:questionnaire).permit(@all_attributes - @not_permitted)
end