I’m trying to refactor my multiple_select code.
Here’s the refactor code:
template:
37 <%= multiple_select f, :company_id, company_select_options(@companies), 38 [prompt: "Choose one or more company.", 39 class: "custom-select w-100 form-control is-invalid",
40 selected: Enum.map(@perfume.companies, &(&1.id)),
41 id: "company_select"] %>
The problem is that when the user input no company, then this @perfume.companies
goes crazy.
The error message: key :companies not found in: %{...
How do I fix it?
One solution I had was to made a companies
key in @perfume
map and set it to nil, in the controller. But it’s ugly.
My current code have a view function that check for if the key exist. Is this the best possible solution?
Current code view:
47 def company_selected(params) do
48 cond do
49 # this is for changeset
50 Map.has_key?(params, :companies) ->
51 company_selected_aux(params.companies)
52 true ->
53 nil
54 end
Thanks!