select box by simple_form in Rails - 保存 id,而不是标题

select box by simple_form in Rails - save id, not title

我在 Rails 应用程序中使用简单表单来生成表单。

架构:

create_table "product_materials", force: :cascade do |t|
    t.integer  "product_id"
    t.integer  "material_id"
    t.integer  "level",       default: 0
    t.integer  "value",       default: 0
    t.datetime "created_at",              null: false
    t.datetime "updated_at",              null: false
  end

型号:

class ProductMaterial < ActiveRecord::Base
  belongs_to :product
  belongs_to :material

  enum level: [:joinery, :grinding, :painting, :assembly]
end

查看:

= simple_form_for [:admin, @product_material], remote: true do |f|
  => f.hidden_field :product_id, value: @product.id
  => f.input :level, collection: [t('product.joinery'), t('product.grinding'), t('product.painting'), t('product.assembly')], label: false
  => f.association :material
  => f.submit t('form.save')

现在是一个问题: 我如何在 select_box 中显示一些 collection 的名称(使用 I18n),但保存多个选定项目(整数)?

How I can in select_box show some collection of names (using I18n), but save a number of selected item (integer)?

ProductMaterial.levels 应该 return 像这样的散列(注意复数形式 levels):

=> {"joinery"=>0, "grinding"=>1, "painting"=>2, "assembly"=>3}

你可以使用它,你所需要的只是制作一个数组数组:

=> ProductMaterial.levels.keys.map{ |x| t("product.#{x}") }.zip(ProductMaterial.levels.values)
#> [[t("product.joinery"), 0], [t("product.grinding"), 1], [t("product.painting"), 2], [t("product.assembly"), 3]]

输入:

=> f.input :level, collection: ProductMaterial.levels.keys.map{ |x| t("product.#{x}") }.zip(ProductMaterial.levels.values), label: false

enum 有很好的文档。