带有来自另一个模型的值的下拉菜单 [英] Drop down menu with value from another model
问题描述
我有属于系列的产品.集合只是一个名称.产品有一个 collection_id.
I have products belonging to collections. A collection is just a name. Products have a collection_id.
在我用于创建和编辑产品的 _form 视图中,我想要一个包含所有集合名称的下拉菜单.
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.
问题,似乎没有附属于 form.for 的选择方法,我正在尝试使用:
Problem, it seems there is no select method affiliated to form.for and i am trying to use :
选择(方法,选择,选项= {},html_options = {})
select(method, choices, options = {}, html_options = {})
来自文档,但我不明白.我必须写一个方法来创建一个表单?有哪些选择,2 个选项?两个参数应该足以填充 <选项>标签.
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?
推荐答案
您可以使用集合选择,首先确保您的模型设置正确:
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) %>
您还可以阅读文档这里.
这篇关于带有来自另一个模型的值的下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!