How to use a select tag with multiple attribute for an has many association in Ruby on Rails
Last week a HasManyThrough
association gave me a headache so I’ve decided to write
down the solution so I can come back to it, but also share it so other people like me
find an answer faster, since it took me like an hour to duck it.
Context
So, in an application I have a many-to-many relationship which I decided to implement
using has_many(through:)
, and while tackling the form for a has_many association
is fairly straight forward (IIRC), I couldn’t for the life of me make the nested
attributes work out-of-the box with the form_with helper.
For this example
Let’s picture a simple case: we want a blog where posts
can have several categories
and we want to manage categories separately for whatever reason.
First attempt: accepts_nested_attributes_for + fields_for
Since I wanted to create a PostCategory
record, using accepts_nested_attributes_for
in conjunction with the fields_for helper made sense to me, since it was actually
dealing with a different model, but seeing the logs quickly made me realize that
I was doing something wrong:
Second attempt: yada yada
I tried different permutations of accepts_nested_attributes_for, didn’t change much.
Nth attempt: read the has_many docs
After feeling more than annoyed I eventually found an old post saying that has_many
associations add <model>_ids
& <model>_ids=
methods, so I had a look and what do
you know? I could skip the attributes joggling and simply add category_ids
to the
accepted parameters from the controller and voilà! It works:
NOTE: that in the parameters we accept a list.
And in your view you can use a native <select multiple> or enhance it with something like select2:
Bonus: nested attributes using JS
If you’re using JSON then it’s easy, just use the correct keys and nest the entries in an array, if you’re using FormData the naming is a bit more cumbersome:
Closing thoughts
As with most things in Rails, the solution is pretty and subtle. When you know it, it feels great; when you don’t, it may feel like a pain in the ass — but if it doesn’t feel right, keep looking!
Or implement your own solution, with blackjack and hookers.
"Confused?" by JoeBenjamin is licensed under CC BY-NC 2.0 .