在Rails中通过simple_form选择框-保存ID,而不是标题

科斯蒂亚·科科斯科(Kostya Kokosko)

我在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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Simple_form(rails)-如果我有params [:id],如何设置默认选择的选项

显示标题而不是搜索结果中的ID

如何在laravel的readmore中传递博客的标题而不是id

Has_many通过复选框(simple_form)无法保存

反应:不是通过单击按钮进行排序 - 通过单击表中的标题“id”进行排序

在url中,如何在rails上的ruby中显示标题名称而不是id?

保存名称而不是Laravel集合中选择组件的ID

下拉列表在Rails中保存ID而不是名称

Rails – 保存现有记录 ID 而不是复制记录

在dplyr中更改一个小标题列以保存标签文本而不是值

如何在Rails 3上使用simple_form在选择选项中强制选择值

如何使用标题而不是ID行来在laravel中选择一行:: find(); 方法

可以通过使用节标题而不是rvsection id来检索节的MediaWiki数据?

Rails Simple_Form多个选择复选框

通过Simple_Form集合进行Ruby on Rails分类

在WooCommerce中通过其ID获取选择的运输方式标题

使用simple_form gem保存了错误的日期

Rails 5中的客户端验证+ simple_form

Rails 4中的关联模型和simple_form

Rails中的动态下拉列表simple_form

单击确认对话框“确定”后,立即在rails 4 + jQuery + simple_form中隐藏按钮

最接近的div作为Rails和Coffee脚本以及simple_form中的引导日期选择器的容器

保存ID而不是名称

Rails回形针显示图像标题,而不是图像

以simple_form呈现动态选择列表

在我的UINavigationBar中的标题中添加图像而不是标题

Rails simple_form嵌套属性

Rails 上的 simple_form 错误

红宝石,simple_form Rails,集合