简体   繁体   中英

How to use a controller variable the in selected field for in collection_select in Rails?

Suppose I have this array variable in my controller: @estudiantes_seleccionados = @clase.estudiantes

Specifically, in:

def set_clase
  @clase = Clase.find(params[:id])
  @estudiantes_seleccionados = @clase.estudiantes
end

How do I use it (@estudiantes_seleccionados) in the selected: field in a collection_select in the view as to preselect the multiple values in the variable when loading the dropdown ?

<%= collection_select(:estudiantes, :id, Estudiante.all, :id, :id_campus, {selected: @estudiantes_seleccionados}, {class: 'form-control', multiple: 'true'}) %>

The problem seems to be multiple: 'true' . When I delete it, only one of the values of @estudiantes_seleccionados gets preselected in the dropdown, but when it is present, none of the values in the array appears.

So, how do I have all the values in @estudiantes_seleccionados the appear as preselected in the dropdown ?

请尝试以下操作:

<%= collection_select(:estudiantes, :id, Estudiante.all, :id, :id_campus, {selected: @estudiantes_seleccionados.map(&:id)}, {class: 'form-control', multiple: 'true'}) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM