09 Oct 2012
nested object forms with checkbox
versions: rails 3.2.8, ruby 1.9.4
Rails is an awesome framework.
You can really concentrate on what you want you make, not how to make it.
One good example is nested object forms.
You dont have to write tons of code in your controller to operate models which has relations like has_many
.
There’s an good tutorial in railscast.com, #196 Nested Model Form Part 1 and #197 Nested Model Form Part 2, so I’m not gonna explain about nested object forms.
I wanted to create an nested object forms using checkboxes just like the below image.
This needs a little twist, if you understand the nested object forms you’ll know why.
I’ll show you how I did this, if there’s any better way to do this, please comment :)
Lets say we have article table and category table, And we want to register multiply category on 1 article by using checkboxes.
The basics(models)
the models will be like the below
form and update method
this is the part which is different from normal nested object forms
view
basically you can’t use fields_for, so you have to write it like this.
update method
If we don’t do this, the checkbox which has been turned off wont be deleted properly.
That’s it! feel free to comment.
Takehiro Adachi at 00:00