Reputation: 282
How do I specify the selected option if two of these options have the same id? I have this form input
<%= f.input :receiver_id,
label: "Client",
collection: receivers_keys_and_values,
as: :grouped_select,
group_method: :last %>
and this method to create the select options
def receivers_keys_and_values
[
["Client", Client.all.map { |c| [c.name, c.id] }],
["Program", Program.all.map { |p| [p.name, p.id] }]
]
end
The issue I have is that a client ID could be the same as a Program ID. Therefore when two ID are the same the selected one is always the Program one. How could I specify something like?
selected: ["Client"][id]
or
selected: ["Program"][id]
Upvotes: 0
Views: 23
Reputation: 6255
This way ids of the selected elements will be different for programs and clients:
def receivers_keys_and_values
[
["Client", Client.all.map { |c| [c.name, "client_#{c.id}"] }],
["Program", Program.all.map { |p| [p.name, "program_#{p.id}"] }]
]
end
You'll also have to update form handling code in order to be able to parse input like "program_123".
You can also go fancy and refactor the code a bit:
def receivers_keys_and_values
[Client, Program].map do |type|
type.all.map { |entity| [entity.name, dom_id(entity) }
end
end
but I'm not sure if it's clearer (should produce the same result though). Up to you.
Upvotes: 1