多个选择集合

时间:2017-09-22 11:40:40

标签: ruby-on-rails simple-form

我知道如何在我的场地上进行多项选择

我有一个像这样的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但它不起作用,我认为来自活动变量类型的问题

1 个答案:

答案 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
  )

经过测试的工作