Antoine Wako
Antoine Wako

Reputation: 145

Multiple select in collection

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

Upvotes: 1

Views: 1100

Answers (1)

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

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"]
    

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

Upvotes: 3

Related Questions