Different implementation on ROR

a 夏天 提交于 2019-12-24 11:12:19

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/3406572/different-implementation-on-ror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!