2017-10-20 26 views
1

看起來像我的表單執行的操作 - 發送正確的值,但不保存在數據庫中。 Check_box_tag需要從enum(我用枚舉,因爲我使用的選擇字段相同的數據):Rails check_box_tag - 將數組保存到Postgres中

class UserProfile < ApplicationRecord 
    enum locations: { Kursenai: 0, Papiskes: 1, Versiai: 2 } 

而在的form_for:

<% UserProfile.locations.each do |key, val| %> 
    <%= f.label key %> 
    <%= check_box_tag('user_profile[locations][]', val, false, id: val) %> 
<% end %> 

但不能更新:

「 [「0」,「1」]'不是有效位置

Postgres:

t.integer "locations", array: true 

因此,我認爲,因爲行類型是integer失敗,但這樣的:

<%= check_box_tag('user_profile[locations][].to_i', val.to_i, false, id: val) %> 

刪除錯誤,但用戶領域:locations仍然nil。我錯過了什麼?

強PARAMS:

..permit(locations: []) 

附:如果您認爲這可以以更好的方式完成 - 請隨時展示。

回答

1

爲什麼?

因爲「[‘0’,‘1’]」被認爲是字符串,它不是在枚舉即提到amoung值你 0,1,2

U可以不能直接作爲實現它枚舉要求字段類型保存單個值。但在 您的情況下它的數組。

如何存檔?

class UserProfile < ApplicationRecord 
    # value should store as array not as string. 
    serialize :locations, Array 

    # define your own enum by creating static var.U can use Array or Hash structure. 
    # Here I am using Hash. 
    # ENUM_LOCATIONS = ["Kursenai", "Papiskes", "Versiai"] 
    ENUM_LOCATIONS = {"Kursenai": 0, "Papiskes": 1, "Versiai": 2} 


    # Now modify you getter little bit to return enumed values 
    def locations 
    res = [] 
    self[:locations].each{|v| ENUM_LOCATIONS.is_a?(Array) ? res << ENUM_LOCATIONS[v.to_i] : res << ENUM_LOCATIONS.key(v.to_i).to_s} 
    res  
    end 

end 

就是這樣

1

你爲什麼使用枚舉?我認爲最好創建一個新的模型位置並通過HABTM關係與UserProfile連接。它將滿足數據庫規範化並更易於使用。

編輯:

class UserProfile < ApplicationRecord 
    has_and_belongs_to_many :locations 
end 

class Location < ApplicationRecord 
    has_and_belongs_to_many :user_profiles 
end 

,你需要創建3個位置記錄

Location.create(name: 'Kursenai') 
Location.create(name: 'Papiskes') 
Location.create(name: 'Versiai') 

使用任何非標準的查詢,聯接。你可以建立像這裏的一種形式: Rails 4 - checkboxes for has_and_belongs_to_many association

Multiple select issue with a HABTM relationship using Rails 4

+0

然後呢?我仍然會在那裏散列enum –

+0

@ J.D。解釋我的觀點更好一點 – kolas

+0

謝謝,@ kolas,但我看不出有這樣的嚴重理由。枚舉是更輕,在這種方法中,我會創建許多靜態對象,而在課堂上包括枚舉看起來更輕的工作。我現在正在處理簡單的字符串數組,並對其進行哈希處理,因爲之後我可能會刪除或向其添加項目。但我想我一定會用這種方式,如果我的字符串數組將成爲對象數組。感謝您的信息。如果我錯了,請糾正我 –

0

看起來有一些命名衝突。我的猜測是,因爲我在模型locations中聲明爲散列,並且稍後允許使用與數組同名的強params屬性。這只是我的猜測。我改名枚舉 - enum locs:和形式 - UserProfile.locs.each和看起來像它正常工作:

class UserProfile < ApplicationRecord 
    enum locs: { Kursenai: 0, Papiskes: 1, Versiai: 2 } 

形式:

<% UserProfile.locs.each do |key, val| %> 
    <%= f.label key %> 
    <%= check_box_tag('user_profile[locations][]', val, false, id: val) %> 
<% end %> 

附:但如您所見,現在我將數據保存爲string[] - ["1", "2"],即使我的db行是 - t.integer "locaions", array: true。想知道爲什麼Postgres允許將字符串數組寫入此行? 不得不重啓服務器