Rails new vs build

Posted by vinhboy on Thursday, January 15th, 2009 in Internet.

@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

7 Comments

  1. Louis-Pierre Dahito Says (January 25th, 2009):

    Thx for sharing… I was having this problem too !

  2. ur girlfriend Says (January 27th, 2009):

    no more laptops in bed?

  3. Steven Says (April 22nd, 2009):

    Thanks – found this with a Google on ‘rails build versus new’

  4. Molte Says (May 24th, 2009):

    By writing
    @comment = @article.comments.new
    the foreign key will also be set.

  5. Ryan Says (July 29th, 2009):

    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

  6. mrbrdo Says (October 27th, 2009):

    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!

  7. cuzic4n Says (March 10th, 2010):

    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

Leave a Comment