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

  • http://dahito.com Louis-Pierre Dahito

    Thx for sharing… I was having this problem too !

  • ur girlfriend

    no more laptops in bed?

  • Steven

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

  • Molte

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

  • Ryan

    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

  • http://blog.mrbrdo.net/ mrbrdo

    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!

  • cuzic4n

    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

  • http://twitter.com/KevinMonk Kevin Monk

    I must’ve visited this blog post about 5 or more times and this comment makes me laugh every time. It’s funny because it’s true.

  • http://twitter.com/l___i Aji

    good

  • wxianfeng

    clean!!!

  • Wander

    Hello everyone :), i like this post,

    Well, i would like to know a litter more  about build and know how to control it in the view….

    i means, if i do something like this:

    5.times {
      @article.comments.build
    }

    in the view will be appears 5 times.

    so, my point is, that i would like to take one of them and give to it a position in a table tag

    some idea about how can i do it?

  • deepak

    Thank You very much , I was looking for this