具有来自另一个模型的值的下拉菜单 [英] Drop down menu with value from another model

查看:14
本文介绍了具有来自另一个模型的值的下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有属于收藏的产品.集合只是一个名称.产品有一个 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 的 select 方法,我正在尝试使用:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆