Multiple select in collection

落花浮王杯 提交于 2020-01-05 04:38:13

问题


I would know how i can allow multiple selection on my field

I have a simple_form field like this

<%= f.input :activity, required: true, autofocus: true, label: "Votre Activité", collection: ["Vente", "Location", "Gestion", "Syndic"] %>

In my controller

devise_parameter_sanitizer.permit(:account_update, keys: [:password, :password_confirmation, :photo, :address, :cover, :activity)

My model

validates :activity, inclusion: { in: %w(Vente Location Syndic Gestion),
        message: "%{value} n'est pas un mandat valide"}

I tried this way but it doesnt work, i think the problem from the activity variable type


回答1:


app/models/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

app/views/.../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
%>
  • I added input_html: { multiple: true } above so that the params will be an array of values instead of just a single value

  • I added that include_hidden: false above because without it you'll get something like

    ["", "Location", "Syndic"]
    

    which adds an empty string instead of just..

    ["Location", "Syndic"]
    
    • more info here

app/controllers/some_controller.rb:

devise_parameter_sanitizer.permit(
  :account_update,
  keys: [
    :password,
    :password_confirmation,
    :photo,
    :address,
    :cover,
    activity: [] # change this from :activity
  )

Tested working



来源:https://stackoverflow.com/questions/46363914/multiple-select-in-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!