Drop down menu with value from another model

人盡茶涼 提交于 2019-11-30 11:40:13

问题


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.



来源:https://stackoverflow.com/questions/5019889/drop-down-menu-with-value-from-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!