Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created April 12, 2012 03:11
Show Gist options
  • Save joshmcarthur/2364410 to your computer and use it in GitHub Desktop.
Save joshmcarthur/2364410 to your computer and use it in GitHub Desktop.
A Nicer Way of Building Records for accepts_nested_attributes_for
class YourModel < ActiveRecord::Base
has_one :listing
accepts_nested_attributes_for :listing
attr_accessible :listing_attributes
# Make sure we always have a listing
after_initialize :build_listing, :unless => :listing
end
@joshmcarthur
Copy link
Author

I've seen various implementations of this before - normally in the controller, or using an after_initialize with a another method. This way is nice because:

  • It only uses ActiveRecord methods - we don't need to define anything anywhere in the controller or elsewhere in the model
  • It will automatically work for both new models and ones pulled out fo the database without a Listing
  • It sets up the implication that we need a Listing for this model, which is nearly always the case when using accepts_nested_attributes_for

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment