Drop down menu with value from another model

2019-02-02 01:01发布

问题:

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?

回答1:

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.