Forum: Ruby on Rails what's the advantage of using build and << ??

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ffd881829651935d986c52d12279befb?d=identicon&s=25 Zhenning Guan (rubyernewbie)
on 2008-12-24 05:32
Rails give us two ways to create a asociation object:
@article = Article.new(params[:article])
@article.comments << Comment.new(params[:comment])
@article.save!
or

@article = Article.new(params[:article])
@comment = @article.comments.build(params[:comment])
@article.save!
@comment.save!

what's the advantage of using build and << ??
9a2a53db8e9b4476038c94a64b32833f?d=identicon&s=25 Ryan Bigg (ryan-bigg)
on 2008-12-24 07:35
(Received via mailing list)
<< should save @article when you add a new comment.
-----
Ryan Bigg
Freelancer
http://frozenplague.net
80e4cb97cae5c8d745f72337d93fd8f2?d=identicon&s=25 MaD (Guest)
on 2008-12-24 10:59
(Received via mailing list)
<< adds records to a association-collection (no matter what kind of
association). it returns itself (the collection) so method calls may
be chained.

btw: in this example @article doesn't have to be saved when a new
comment is added (comment has article_id as foreign key). ;-)
80e4cb97cae5c8d745f72337d93fd8f2?d=identicon&s=25 MaD (Guest)
on 2008-12-24 11:02
(Received via mailing list)
just saw that this could be misunderstood:
article has to be saved to be able to make a association, but it
doesn't have to be saved after adding a new comment.
Ffd881829651935d986c52d12279befb?d=identicon&s=25 Zhenning Guan (rubyernewbie)
on 2008-12-24 15:29
MaD wrote:
> << adds records to a association-collection (no matter what kind of
> association). it returns itself (the collection) so method calls may
> be chained.
>
> btw: in this example @article doesn't have to be saved when a new
> comment is added (comment has article_id as foreign key). ;-)


what's  does that -method calls may be chained-? can you make me a
concrete example?



in this example @article doesn't have to be saved when a new
> comment is added (comment has article_id as foreign key)
=
@article = Article.new(params[:article])
don't we have to save it for store a Article instance?
This topic is locked and can not be replied to.