Javier Valencia
Javier Valencia

Reputation: 695

Different implementation on ROR

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.

Upvotes: 1

Views: 162

Answers (1)

Zachary Wright
Zachary Wright

Reputation: 24070

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

Upvotes: 4

Related Questions