2 parts:
1st for general explanation of nested attributes
2nd for join model case – so jump in straight to it if you’re ready
3rd – other ways of handling multiple resources in rails
topics to cover: different ways, routing, validations, client-side validations, inverse_of, blanks, accesible attributes, json requests.
Part 1: nested attributes demystified
As a Rails newbie who switched from PHP the thing I like most in Rails is … convention over configuration. I am quite a creative coder, so I can write things in many different ways, which sometimes drives me crazy deciding which one is the best. In rails there is a rails way of doing things and for most of my rails coding history I desperately try to stick with it. Sometimes it’s ease, other times hard – like with sparsely documented features and such. Nested attributes is the case here. (accepts_nested_attributes_for).
1st big question for a rails newbie – handling multiple resources in one view/controller. There are not many resources on this topic, and sooner or later you stumble on it.
When I had to deal with creating/updating multiple associated resources in one view – questions appear for a rails freshman: how to keep it dry, how to stay skinny on the controller side and put all the fat in the model, how to utilize rails resources most efficiently without hundreds of sqls send in the bg, how not to break to many REST conventions etc. – in other words how to do it as rails way as possible.
Then I stumbled upon accepts_nested_attributes_for feature added in rails xxx (check for version no) which looked like a perfect solution. After scanning the docs [1], [2]. reading some blogs [3],[4] and finally watching Ryan Bate’s screencast [5], I’ve decided to have a go on this. And I have tripped and stumbled. Oh I have. And I have risen up again to finally get this all done correctly. There are many big and small gotchas on the way (like misspelling resource_ids, forgetting about inverse_of, and alike) which I want to sum up in this post. So let me walk you through creating nested model form for a double nested join model and explaining everything on the way, the way I learned it.
Part 2: nested attributes for join model
[1] http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for
[2] http://apidock.com/rails/v3.2.13/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for
[3] http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
[4] http://weblog.rubyonrails.org/2009/1/26/nested-model-forms/
[5] http://railscasts.com/episodes/196-nested-model-form-revised