我知道如何在我的场地上进行多项选择
我有一个像这样的simple_form字段
<%= f.input :activity, required: true, autofocus: true, label: "Votre Activité", collection: ["Vente", "Location", "Gestion", "Syndic"] %>
在我的控制器中
devise_parameter_sanitizer.permit(:account_update, keys: [:password, :password_confirmation, :photo, :address, :cover, :activity)
我的模特
validates :activity, inclusion: { in: %w(Vente Location Syndic Gestion),
message: "%{value} n'est pas un mandat valide"}
我试过这个way但它不起作用,我认为来自活动变量类型的问题
答案 0 :(得分:0)
应用/模型/ your_model.rb 强>:
class YourModel < ApplicationRecord
serialize :activity, Array # add this
# you can't use `inclusion:` validation because it is only for validating a single value
# so you'll do something like this, or if you want it to clean it a bit by defining a method instead, see here https://stackoverflow.com/questions/13579357/validates-array-elements-inclusion-using-inclusion-in-array
validate do
unless %w(Vente Location Syndic Gestion).include? activity
errors.add(:activity, "#{activity} n'est pas un mandat valide"
end
end
end
应用/视图/.../ some_view.html.erb 强>:
<%= f.input :activity,
required: true,
autofocus: true,
label: "Votre Activité",
collection: ["Vente", "Location", "Gestion", "Syndic"],
input_html: { multiple: true },
include_hidden: false
%>
我在上面添加了input_html: { multiple: true }
,因此params
将是一个值数组而不是一个值
我在上面添加include_hidden: false
因为没有它你会得到类似
["", "Location", "Syndic"]
添加空字符串而不仅仅是..
["Location", "Syndic"]
应用/控制器/ some_controller.rb 强>:
devise_parameter_sanitizer.permit(
:account_update,
keys: [
:password,
:password_confirmation,
:photo,
:address,
:cover,
activity: [] # change this from :activity
)
经过测试的工作