2015-08-15 36 views
0

我在Rails應用程序中使用Simple Form來生成表單。通過rails中的simple_form選擇框 - 保存id,而不是標題

模式:

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),但保存一些選定的項目(整數)?

+0

我不完全確定這個,但我認爲你可以傳遞一個數組作爲'collection'選項。 'f.input:level,collection:[[t('product.joinery'),:joinery],...]'。試試看。 – max

+0

這可能的原因是['options_for_select']](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select)接受'[[text,value]]'陣列的選項。 – max

回答

1

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

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有一個很好的文檔。

+0

Tnx爲你的答案,但出了問題... 地圖工作正確,查看渲染正確了,但提交後,我有錯誤:'ArgumentError('1'不是一個有效的水平)' 如果我創建記錄控制檯中的所有參數都正常工作 –

+0

僅使用'ProductMaterial.levels.keys.map {| x | t(「product。#{x}」)} .zip(ProductMaterial.levels.keys)enum字段只允許在這個散列中使用'keys'而不是值,所以'1'不是enum字段的'level'值, '繪畫'是有效的級別,就像''enum'在'Rails'中工作。 –

+0

woohoo !!現在一切正常! ,但爲什麼控制檯中的ProductMaterial.create(product_id:21,level:0,material_id:44,value:5)正確並創建新記錄? 'value'字段只是一個整數,'1'或'0'必須是正確的參數... –