1

I have a Rails 5 app.

template _form

- if current_user&.super_admin
  .form-group.has-feedback
    .text-muted
      = f.label 'Which users should see this?'
    = f.collection_select(:user_templates, User.all, :id, :name, { include_hidden: false }, multiple: 'true', class: 'select')

It's a multiple select form. When submitting the form I send an array of users to my controller and save it in my user_template table, which creates a new row for every users that was selected. Works perfectly.

However, when I edit the specific template I would like to show the users that was saved the first time. I can easily query them in the db and get all the right users but I cannot show them as selected in the multiple dropdown.

Any ideas?

Andy
  • 531
  • 1
  • 4
  • 19
  • 1
    https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select#632--selected – Eyeslandic Feb 20 '18 at 09:25
  • Thanks for the comment @Iceman. I have tried adding `{ :selected => User.all }` and I would expect all users to be selected in the dropdown. However, none are selected. Any ideas why that is? – Andy Feb 20 '18 at 09:30
  • 1
    Got it to work mate. This is my new f.collection_select: `= f.collection_select :user_templates, User.all, :id, :name, { :selected => User.all.map(&:id)}, multiple: 'true', class: 'select'` – Andy Feb 20 '18 at 09:32
  • Great, I also think the shorthand `User.all.ids` works, if I remember correctly. – Eyeslandic Feb 20 '18 at 09:33
  • 1
    Just tried and it does indeed work. Cheers. – Andy Feb 20 '18 at 09:35
  • @Iceman: I'm having issues with my query for the active record entries. I have the following tables `template`, `user`, `template_user` and user has_many templates through: `template_user`. I would like to return a list of all the users for a given template id. Does that make sense? – Andy Feb 20 '18 at 09:48
  • If you have in your `Template`model a reverse of that relationship, `has many :template_users` and `has_many :users, through: :template_users`. It's just a matter of `Template.find(1).users` – Eyeslandic Feb 20 '18 at 10:15
  • Doh! So simple. Makes sense. Works. Thanks. – Andy Feb 20 '18 at 10:18

0 Answers0