Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

2009 07 21: Nested Attributes


Published on

How to use simple forms with nested models and single access points into web api's without the view or controller logic getting messy. Demonstration of the Rails 2.3 accepts_nested_attributes_for feature

Published in: Technology
  • Be the first to comment

  • Be the first to like this

2009 07 21: Nested Attributes

  1. 1. Wolfram Arnold Nested Attributes <ul><ul><li>CRUD </li></ul></ul><ul><ul><li>on multiple models </li></ul></ul><ul><ul><li>without crud </li></ul></ul>
  2. 2. Associations <ul><li>class Pirate < ActiveRecord::Base has_one :ship end </li></ul><ul><li>class Ship < ActiveRecord::Base belongs_to :pirate end </li></ul>
  3. 3. User Interface? <ul><li>Form with pirate and ship fields </li></ul><ul><ul><li>form_for :pirate do |pf| pf.text_field :catchphrase pf.fields_for :ship do |sf| sf.text_field :name end # params[pirate][ship] # Note: broken! end </li></ul></ul>
  4. 4. Controller Interface? <ul><ul><li>def create @pirate =[:pirate]) @ship =[:pirate][:ship]) @ship.pirate = @pirate if && ... else # what about rollback? end end </li></ul></ul>
  5. 5. Demo
  6. 6. Fat model/skinny controller <ul><li>Logic in the model, not views/controllers </li></ul><ul><li>Assignments </li></ul><ul><ul><li>class Pirate < ActiveRecord::Base def ship_attributes=(attrs) ... end end </li></ul></ul><ul><li>Validations handled in model, incl. child models </li></ul>
  7. 7. Saving—when? <ul><li>:autosave => true flag, new in Rails 2.3! </li></ul><ul><li>Automatically turned on for accepts_nested_attributes_for </li></ul><ul><li>Parent will save all children </li></ul><ul><ul><li>New parent, modified children </li></ul></ul><ul><ul><li>Existing parent, new/modified children </li></ul></ul><ul><ul><li>As a transaction—rollback on validation failure </li></ul></ul><ul><ul><li>Cascaded error messages </li></ul></ul><ul><li>Removes a lot of confusion </li></ul><ul><li>Demo </li></ul>
  8. 8. Web Service API <ul><li>PirateController and ShipController? </li></ul><ul><li>Not advised if </li></ul><ul><ul><li>Objects have a relationship, e.g. has_one association </li></ul></ul><ul><ul><li>Dependencies </li></ul></ul><ul><ul><li>Business logic rules/validations </li></ul></ul><ul><li>Better single API with nested attributes </li></ul><ul><ul><li>Simpler client code </li></ul></ul><ul><ul><li>Less network traffic </li></ul></ul>
  9. 9. References <ul><li> </li></ul><ul><li> </li></ul><ul><li> </li></ul><ul><li>Advanced Rails Recipes, Pragmatic Programmer Series </li></ul>
  10. 10. Wolfram Arnold <ul><ul><li>Thank you! </li></ul></ul>