2011-05-04 93 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或者你需要的任何地方使用它。这应该让事情变得更加清洁,并且在你的粗暴行动中更加“轨道化”。

相关问题