Could you help me to display the data of a HASH in a select of my view. I have my hash data in the view but I need the option value to have the IDs.
Rails 5.2.2
<div class="form-group row"><label class="col-sm-2 col-form-label">Select</label>
<div class="col-sm-10">
<%= f.select(:prevision, Usuario::PREVISION.collect{ |u| [u]}, {prompt: 'Seleccionar tipo de previsión'}, {:class=>'form-control m-b',readonly: true ,required: true}) %>
</div>
</div>
view inspected code
<div class="form-group row"><label class="col-sm-2 col-form-label">Select</label>
<div class="col-sm-10">
<select class="form-control m-b" readonly="readonly" required="required" name="paciente[prevision]" id="paciente_prevision"><option value="">Seleccionar tipo de previsión</option>
<option value="FONASA">FONASA</option>
<option value="ISAPRE">ISAPRE</option>
</select>
</div>
</div>
MODEL
class Usuario < ApplicationRecord
FONASA = 1
ISAPRE = 2
PREVISION = [
:FONASA,
:ISAPRE
]
end
CodePudding user response:
First you need to fetch them in your controller like so
@prevision = Usuario::PREVISION
Then you can add them in your .erb
file like so:
<select class="form-control m-b" readonly="readonly" required="required" name="paciente[prevision]" id="paciente_prevision"><option value="">Seleccionar tipo de previsión</option>
<% @prevision.each do |p| %>
<option value="<%= p %>"><%= p %></option>
<% end %>
</select>
To add on based on @engineersmnky's comment, if you want it to be a hash then you need to make your model have:
PREVISION = {
'1': 'FONASA',
'2': 'ISAPRE',
}
Then you need to change your views code to:
<select class="form-control m-b" readonly="readonly" required="required" name="paciente[prevision]" id="paciente_prevision"><option value="">Seleccionar tipo de previsión</option>
<% @prevision.each do |key, value| %>
<option value="<%= key %>"><%= value %></option>
<% end %>
</select>