Forum: Ruby on Rails Does has_many collection '<<' (append operator) always save/create child in DB when parent isn't ne

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.
Kendall G. (Guest)
on 2009-06-02 02:21
(Received via mailing list)
Howdy, the title mostly asks the question.

Given the following:

class Article < ActiveRecord::Base ; has_many :comments ; end
class Comment < ActiveRecord::Base ; belongs_to :article ; end

I have an article already instantiated in the database, referenced as
@article.

Will the following code always "create" (save to DB) a new comment?

@article.comments << Comment.new :text => "Blah blah..."

I would like to be able to add comments to an article that already
already exists (and may already have comments that exist) in the
database w/out the new comment being saved to the database.

I would try this: @article.comments.build :text => "Blan blah..."

The reason I don't is because my Comment class is sub-classed using
STI. Thus, my code really looks more like this:

klass = Comment.get_class(params[:comment_type]) # get_class returns
Comment or a sub-type
@article.comments << klass.new :text => "Blah blah..."

Anyone have any ideas on how I can add STI comments to an article w/
out saving them, doing so "the right way" (I'm sure I could ugly-hack
it)?

Thanks.
This topic is locked and can not be replied to.