We are working with nested attributes and we’ve reached a point where we’re not sure if there is a better, clearer, “more rails” way of dealing with it.
We have 3 models - Organisation, Category and a strictly join table CategoryOrganisation (no additional attributes). The relation between Organisation and Category is many-to-many.
Now, we want to create a form with checkboxes through which the categories for organisations can be added and removed. The example form would look like that:
Now, the form should behave like that:
- when
new
action is hit, it should show all categories - unchecked, - when
create
action is hit, but validations are not passing it should render thenew
view, but keeping the checkboxes that were selected, - when
edit
action is hit, is should show all categories and current categories of the edited organisation should be checked, - when
create
andupdate
are successful, flow is redirected toshow
action. We don’t want to spoil your minds with our custom solution, but to get to know if there is a clear, Rails solution for that.
In our opinion, there is no such solution in Rails documentation, as we found out reading following sources:
- http://guides.rubyonrails.org/form_helpers.html,
- http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html,
- http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html. API documentation doesn’t get to many-to-many relation, which is the case in our app.
In advance, thanks for help!