ruby on rails active record garbage collection questions (ruby 1.8.7 and rails 2.3.5)
I have the following entities : brand, scoring_records. Brand has_many scoring_records.
If I have a block where I am working on a brand like this:
brands.each{|brand|
# do some stuff
brand.do_some_stuff
some_scoring_records = ScoringRecords.find(:all,:conditions => ["computed_date = ?",today], :order => 'brand.id' )
# do some more stuff
brand.do_some_more_stuff(brand)
brand.do_even_more_stuff(brand)
}
question 1: When I load scoring_records like this, does it associate it with the brand automatically in rails (or does it wait for the relationship to be exercised. In other words in do some more stuff are the scoring records still around if I call brand.scoring_records, will it call to the database?, or eligible for garbage collection? (Im guessing they are not, because the brand has the relation to scoring_re开发者_StackOverflowcords, so since brand is referenced later, and not eligible, neither are any of the scoring_records. Is there a way to load these without the association?
question 2: If the records will not be gc'd, is there anyway to make the scoring_records eligible for gc, but keep the brand around, and the rest of its relationships? I dont want to delete the scoring_records, I just want to remove them from memory.
Question 1: scoring_records is a local variable that is not available in do_some_more_stuff. The scoring_records that is added by has_many is not a variable, it's a method, and you cannot assign to it. You need to read up on variable scopes. This is a good start: http://www.techotopia.com/index.php/Ruby_Variable_Scope. The scoring_record variable in the code you have supplied has no effect on the scoring_records in the brand variable.
If this code were in the brand class, it would assign the scoring records returned by the find to the association, associating it immediately, but persisting only when saved. Not for the brand variable, but for the object itself.
Question 2: scoring_records aren't related to brand, its scope is the block.
精彩评论