【问题标题】:Different implementation on RORROR 的不同实现
【发布时间】:2010-08-04 14:34:23
【问题描述】:

我正在使用 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 方法有什么不同。

附注对不起我的英语。

【问题讨论】:

    标签: ruby-on-rails performance implementation


    【解决方案1】:

    他们都将执行相同的工作。

    :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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多