我在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中显示一些名称集合(使用I18n),但是保存一些选定的项(整数)?
如何在select_box中显示一些名称集合(使用I18n),但如何保存一些选定的项(整数)?
ProductMaterial.levels
应该返回一个哈希,例如(注意复数形式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
有一个很好的文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句