LogofaT
LogofaT

Reputation: 289

How do I add a select (dropdown) to my generated form?

How can I add a select field in a form if that is generated for a model?

My controller sends the array that should be used to populate the select.

Controller:

def new
  @categories= Category.all
  @product= Product.new
end

The Category model has an id and a label.

The form looks like:

=form_for :product do |f|
- if @product.errors.any?
#error_explanation
  %h2
    = pluralize(@product.errors.count, "error")
    prohibited
    this product from being saved:
  %ul
    - @product.errors.full_messages.each do |msg|
      %li= msg
%p
  = f.label :title
  %br
  = f.text_field :title
%p
 = f.label :category_id
 %br
 = f.xxxxxxxxx
%p
  = f.submit

xxxxxxxxx is the place where I need the select populated by the @categories array.

Upvotes: 1

Views: 69

Answers (2)

AndyV
AndyV

Reputation: 3741

I'd avoid @NARKOZ suggestion for two reasons. The most important is that it embeds logic that should be in the controller (fetching the Category records) into the view. That's poor separation. Second, there's a very convenient collection_select method that accomplishes the same thing.

= f.collection_select :category_id, @categories, :id, :name, {prompt: 'Pick a category'}, { class: 'select-this' }

This assumes that you have loaded a @categories instance variable in the controller as you had in your question.

Note that this method takes two optional hashes at the end. The first hash accepts the usual options for the select method. The second hash accepts HTML options (e.g., HTML style, class, etc., attributes).

Upvotes: 1

NARKOZ
NARKOZ

Reputation: 27961

= f.select :category_id, @categories.collect {|c| [ c.name, c.id ]}

where @categories is Category.all

Upvotes: 2

Related Questions