Software dev, tech, mind hacks and the occasional personal bit

Rails ActiveModel, with nested objects and validation

So maybe you have a model that is not backed by a database table? ActiveModel is meant to cover this scenario and give you the usual ActiveRecord goodness and validation.

But the story gets much harder if you want to have nested objects. In a normal ActiveRecord::Base backed model, you can simply say:

accepts_nested_attributes_for :order_lines

and Rails will manage form submitted nested parameters for you.

Life is not so simple, or documented with nested objects on ActiveModel. accepts_nested_attributes_for is not available. But some of the underpinnings are.

So enough talk, how do you make it work? I’ll show you with an Order / OrderLines example.

Note the very special name: order_lines_attributes=. This hooks into the Rails handling of nested form parameters. Also the valid? method propagates the child errors up to the parent object, so that they show up at the top of the form.

Now how do you do the nested form? It’s similar to normal database backed nested records.

Hope this helps, it is not documented anywhere I could find, and worked out mainly though reading the Rails source.

Previous

Rails: Removing error divs around labels

Next

“Selling the Invisible” by Harry Beckwith

2 Comments

  1. Thanks, you helped me a lot.

  2. Iksflow

    Thanks!
    Your article saved me.

Leave a Reply to Guilherme Cancel reply

Your email address will not be published. Required fields are marked *

Powered by WordPress & Theme by Anders Norén