Rails: form_for 带有供用户选择的子模型

Rails: form_for with submodel for user selecting

例如,我有一个 product 模型。每个产品有一个名为 ProductTypetype。现在我想创建产品。

这是我使用 slim 的简单形式:

= form_for @product, url: product_path, :html => {:method => post} do f
  = f.label :name
  = f.text_field :name
  = f.submit 'Create'

我想要这个表格,有一个下拉列表列出所有类型的产品(从 ProductType 加载),用户可以选择一个。我如何在 rails 中执行此操作(使用 form_for

谢谢

collection_select 正是为此目的而构建的。

假设ProductType有一个name属性,试试

= form_for @product, url: product_path, :html => {:method => post} do f
  = f.label :name
  = f.text_field :name

  # collection_select creates a select box with the options set from the collection
  = f.label :type
  = f.collection_select :type, ProductType.all, :name, :id

  = f.submit 'Create'

查看文档: http://apidock.com/rails/v4.2.7/ActionView/Helpers/FormOptionsHelper/collection_select