2010-08-04 44 views
1

我正在用ROR製作一個非常簡單的網站。ROR上的不同實現

class Product < ActiveRecord::Base 

    belongs_to :category 

    has_many :photos 

    has_many :ordered_photos, 
       :class_name => 'Photo', 
       :order => 'name' 

    has_one  :random_photo_1, 
       :class_name => 'Photo', 
       :order => 'RAND()' 

    def random_photo_2 

     Photo.find(:first, :conditions => { :product_id => self.id }, :order => 'RAND()') 

    end 

end 

在實現許多類的ActiveRecord的,我得到的疑問,我不理解那是什麼random_photo_1執行之間的random_photo_2方法不同。

P.S.我很抱歉我的英語。

回答

4

他們都會執行相同的工作。

random_photo_1的好處在於,無論何時查找多個產品,您都可以輕鬆加載所有「隨機照片」關聯,如果您要展示大量產品和他們的任意照片在您的視圖。

#:include will eagerly load the associations 
@products = Product.find(:all, :include => :random_photo_1) 

然後,每當你在你的看法遍歷@products,如果你這樣做:

@products.each do |product| 
    #This will not do a new select against the database 
    <%= product.random_photo_1 %> 
end