Rails new vs build
@article = Article.new
Creates a new instance of a Model.
@comment = @article.comments.build
Just like the new method, but by assocation proxies (not for Models). It automatically sets the foreign_key.
The other thing is that when you are doing a “has_one” the build looks like this:
@comment = @article.build_comments
I am writing this posts because searching “rails new vs build” on google did not yield any good results. I found my answer with the help of a friend, and through this post here: http://railsforum.com/viewtopic.php?pid=39621#p39621
Thx for sharing… I was having this problem too !
no more laptops in bed?
Thanks – found this with a Google on ‘rails build versus new’
By writing
@comment = @article.comments.new
the foreign key will also be set.
Another big thing is that @article.comments.build doesn’t save the comment until @article is saved. Whereas if you do:
@comment = Comment.new
@article.comments << @comment
@comment is saved right then even if @article later fails validation and is never saved you will still have @comment in the comments table
I did some further research into new vs. build vs. create in Ruby on Rails, which someone might fight useful.
My observations and code examples can be found in my blog post here: http://blog.mrbrdo.net/2009/10/27/ruby-on-rails-new-vs-create-vs-build/
I also included some comments from this blog post. I hope this information will be useful to someone!
i was wondering why my “comments” validation routines were not going off.. it was because i was using the append “<<"..
so i started searching around for new vs build create rails.. and came across build..
@article.comments << @comment .. will not trigger validation routines.
@c = @article.comments.build
set @c to stuff. and try @c.save or @c.save! you will see that the validation routines in the comment model go off as expected which is what i needed