Wolfram Arnold www.rubyfocus.biz Nested Attributes
CRUD
on multiple models
without crud
Associations
class Pirate < ActiveRecord::Base has_one :ship end
class Ship < ActiveRecord::Base belongs_to :pirate end
User Interface?
Form with pirate and ship fields
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
Controller Interface?
def create @pirate = Pirate.new(params[:pirate]) @ship = Ship.new(params[:pirate][:ship]) @ship.pirate = @pirate if @pirate.save && @ship.save ... else # what about rollback? end end
Demo
Fat model/skinny controller
Logic in the model, not views/controllers
Assignments
class Pirate < ActiveRecord::Base def ship_attributes=(attrs) ... end end
Validations handled in model, incl. child models
Saving—when?
:autosave => true flag, new in Rails 2.3!
Automatically turned on for accepts_nested_attributes_for
Parent will save all children
New parent, modified children
Existing parent, new/modified children
As a transaction—rollback on validation failure
Cascaded error messages
Removes a lot of confusion
Demo
Web Service API
PirateController and ShipController?
Not advised if
Objects have a relationship, e.g. has_one association
How to use simple forms with nested models and sing more
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 less
0 comments
Post a comment