Load options from a table in Ruby on Rails

-1

I have 2 tables with their respective model and controller. One is productos and other marca . I did a scaffold for both. In the product form I put a select with the idea of loading the options based on the data in the table marcas ( marcas , only has id and nombre ). How can I do this?

    
asked by Luis Fernando Quintero 10.03.2017 в 21:57
source

2 answers

1

Rails gives you different alternatives to do this.

Previous Note: Because of your question it is not possible to know if the brand is a product association. I will assume that this is the case because it would make more sense. If it is not, instead of passing the value id you would have to pass name

1) Using options_from_collection_for_select ()

This helper the rails allows you to do exactly this. You need a minimum of 3 arguments: the collection, the value to pass to the form and the value to be shown in the form.

# Tu Vista
...
<%= f.select :marca_id, options_from_collection_for_select(Marca.all, :id, :nombre) %>

More info on this method here

2) Using collection_select ()

The result is very similar to the previous one. Take the same arguments.

# Tu Vista
...
<%= f.collection_select :marca_id, Marca.all, :id, :nombre %>

More info on this helper here

3) Using pluck to create your collection

If we do not want to use the rails helpers we can do this. As recommended by Alter Lagos, it should be done in a helper to avoid soiling the view (in which there should be the least logical possible).

#app/helpers/tu_helper.rb
...
def marcas_for_select
  Marca.all.pluck(:id, :nombre)
end

# Tu vista
...
<%= f.select :marca_id, marcas_for_select %>

4) Using map to create your collection

Pluck is undoubtedly the most efficient when we want to use for the select fields of the database. But what happens if we want to use a method created in the model. For example:

#app/models/marca.rb
...
def nombre_con_id
  "#{self.id}-#{self.nombre}"
end

In that case pluck does not work for us and we use map

#app/helpers/tu_helper.rb
...
def marcas_con_metodo_decorado
  Marca.all.map { |m| [m.id, m.nombre_con_id]}
end

<%= f.select :marca_id, marcas_con_metodo_decorado %>

Notes:

  • To make it shorter I created the collection in the view (Marca.all) but it is not good practice. You should create it in the controller and pass it as a class variable.
answered by 11.03.2017 / 17:08
source
1

In a helper put something like:

def marcas_for_select
   Marcas.pluck(:nombre, :id)
end

then in your form you use:

<%= f.select(:marca_id, marcas_for_select, { include_blank: 'Seleccionar Marca' }) %>
    
answered by 10.03.2017 в 23:46