views:

51

answers:

1

I'm making a very simple website with 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

During implementing many classes of ActiveRecord, I get doubt, I don't understanding what it's the different between random_photo_1 implementation a random_photo_2 method.

P.S. I'm sorry for my english.

+4  A: 

They will both perform the same job.

The benefit of :random_photo_1 is that you can easily eager load all the "random photo" associations whenever you do a find for several products, which would really help performance if you're going to show a lot of products and a random photo of them on your view.

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

Then, whenever you are iterating over @products on your view, if you do:

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