2011-05-04 72 views
0

我使用simple_form並有下面的示例代碼:軌帶回所有複選框,而不是隻選一個

<%= f.input :medical_conditions, :label=>false, :collection => medical_conditons, :as => :check_boxes%> 

收集持有約100複選框。但是,當用戶只選擇1或2,一切都還是會被保存到數據庫中是這樣的:

--- 
- "" 
- "" 
- "" 

medical_conditions是我application_helper

def medical_conditons 
t = [ 
    "Allergies/Hay Fever", 
    "Diabetes", 
    "Heart Surgery"] 
return t 
end 

medical_conditions領域一個簡單的數組是:string場。

我需要做什麼以便只有選定的值以逗號分隔的方式保存。

回答

1

嘗試這樣的事情在你的控制器(你怎麼寫你創建/更新方法是猜測)...

params[:medical_conditions].delete('') #this will remove the empty strings 
@instance.update_attribute(:medical_conditions, params[:medical_conditions].join(',')) 
#or however you want to save the input, but the key is the .join(',') which will 
#create a comma-separated string of only the selected values, which is exactly 
#what you're looking for me thinks :-) 

如果做的伎倆爲你,我會考慮做一個私人助手方法,它爲你設置參數的格式,以便你可以在#create,#update或者你需要的任何地方使用它。這應該讓事情變得更加清潔,並且在你的粗暴行動中更加「軌道化」。

相關問題