ROR的不同实现 [英] Different implementation on ROR

查看:82
本文介绍了ROR的不同实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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

在实现许多ActiveRecord类期间,我怀疑,我不了解random_photo_1实现与random_photo_2方法之间的区别.

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.我为我的英语感到抱歉.

推荐答案

他们将执行相同的工作.

They will both perform the same job.

:random_photo_1的好处是,无论何时找到几种产品,您都可以轻松地渴望加载所有随机照片"关联,如果您要展示很多产品和随机显示,这确实对性能有帮助.他们在您看来的照片.

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)

然后,只要您在视图上遍历@products,就执行以下操作:

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

这篇关于ROR的不同实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆