I have a parent and child model relationship. In the child's migration.rb, the child model's columns each have default values (except the parent_id column).
When I make a new parent object, how can I make it so that a child object is created and saved into its table with the data from the default values along with the parent_id?
I'm thinking that it will have to do with something like an after_create
on the parent model, but I'm not sure how to set it up.
You didnt specify (or I overread it) what kind of relationship you are using. If you are using a one-to-one relationship, such as "has_one" create wont work. In this case you have to use something like this:
in parent.rb
after_create might work as well, havent tested that.
while in child.rb
I was struggling with this quite a bit when setting up a user model in my current application.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html You can see that has_one does not support parent.build or parent.create
Hope this helps. Im new to Ruby myself and slowly starting to make my way through the Ruby jungle. A nice journey but easy to get lost in. :)
Revised: I revised the answer to use before_create and building, not creating, the associated models. The ActiveRecord machinery then takes care of saving the associated models once the parent is saved.
I even tested this code!
Added...
The build method is added by the owning model's machinery by the has_many statement. Since the example uses has_many :doors (model name Door), the build call is doors.build
See the docs for has_many and has_one to see all of the additional methods that are added.
Rails 2.x introduced the autosave option for associations. I don't think it applies to the above (I'm using default). Autosave testing results.