Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop down menu with value from another model

I have products belonging to collections. A collection is just a name. Products have a collection_id.

In my _form view that is used for creation and edition of products, i'd like to have a drop down menu with the name of all collection.

Problem, it seems there is no select method affiliated to form.for and i am trying to use :

select(method, choices, options = {}, html_options = {})

from the doc but i do not understand it. I must write a methode to create a form? What are the choices, and the 2 options? Two parameters should be enough to populate an < option> tag.

How can I have a drop down menu alowing me to assign a collection through collection name to my product?

like image 814
Syl Avatar asked Feb 16 '11 17:02

Syl


1 Answers

You can use a collection select, first make sure your models are properly setup:

class Product
  belongs_to :collection
end

class Collection
  has_many :products
end

Then add the collection select to your view:

<%= collection_select(:product, :collection_id, Collection.all, :id, :name) %>

You can also read up on the documentation here.

like image 172
Pan Thomakos Avatar answered Oct 19 '22 21:10

Pan Thomakos