Update Child Model From Parent’s Attributes in Rails
You probably already know that you can add child models relationships through the parent model once you have set up your models appropriately:
BlogPost < ActiveRecord::Base
has_many :comments
end
Comment < ActiveRecord::Base
belongs_to :blogpost
end
..and then you can do something like:
@blog = BlogPost.new(:title => "My First Post")
@comment = Comment.new(:body => "Great Post!")
@blog << @comment
@blog.save
We use the << method to make a foreign key relationship. When we save the blogpost model, it automagically saves the @comment model, and associates it with blogpost record via a foreign key, so that we can later say
puts @blog.comment.first.body
# "Great Post!"
But, what you may have not known about is Nested Attributes. This is a slick little feature, turned off by default, that allows you to create the child model via parameters of the parent model. To enable it, simply add this method call to the parent model:
BlogPost < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
end
Now, you can create the same blog/comment models & relationship with a quicker syntax:
@blog = BlogPost.new(:name => "My First Post", :comments_attributes => [{ :body => "Great Post!" }])
@blog.save
Upon saving, this will create the BlogPost, create the Comment, and set up the foreign key relationship. Sick!
To learn more, check out: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html