0

I want to pass conditional parameters based on selections (yes/no responses to 3 individual checkboxes) in the input form. I tried using the if then else approach but that is clearly not elegant due to 8 different options. Can someone please provide a better solution?

I came across the following post and tried my interpretation but could not figure out the correct answer.

Strong Parameters: How to permit parameters using conditions

Expected outcome: If a given checkbox is clicked that particular nested model gets updated / instance created, else not

My attempt at the parameters

def lapp_params
  list_params_allowed = [:amount]
  list_params_allowed += [:cond1_attributes[:name, :country]] if params[:lapp][:ind_var1]==1
  list_params_allowed += [:cond2_attributes[:name,:course]] if params[:lapp][:ind_var2]==1
  list_params_allowed += [:cond3_attributes[:name,:company]] if params[:lapp][:ind_var3]==1

  params.require(:lapp).permit(list_params_allowed).merge(user_id: current_user.id)
end
Community
  • 1
  • 1

1 Answers1

0

In order to scale to 8 or even more, I would put your repetitive logic in a loop. Then abstract the dynamic parts (in bold below) into an array.

list_params_allowed += [:cond1_attributes[:name, :country]] if params[:lapp][:ind_var1]==1

The array would look something like this:

possible_conditions = [
    {number: "1", value: "country"},
    {number: "2", value: "course"}
]

Then you could loop over your array in the following manner:

possible_conditions.each { |pc|
  list_params_allowed += ["cond#{pc[:number]}_attributes"[:name,pc[:value]]] if params[:lapp]["ind_var#{pc[:number]}"]==1
}

It is OK to replace your constant symbols such as :cond1_attributes with an interpolated string because this is functionally equivalent. Hope this helps!