开发者

ActiveRecord - pre fetch single records from association

Consider the following models..

class Product < ActiveRecord::Base
  has_many    :pricings
end

class Pricing < ActiveRecord::Base
  belongs_to  :server
end
开发者_如何学运维

Pricing is a historical tracking table for prices of products, so there may potentially be hundreds of price points captured over time. What I want to add is a way to get only the current pricing for the product.

While i can add a has_one relation to the model like the following:

has_one  :current_pricing, :class_name => "Pricing", :foreign_key => "product_id",
         :order => 'created_at DESC'

This will fetch me all the Pricings for the current product before returning me only the first record.

I am looking for a way to accomplish this in a more efficient manner and was hoping that someone would have input or previous experience doing something similar.


You could use a named scope. Put this at the top of the Pricing model:

class Pricing < ActiveRecord::Base
  named_scope :current, lambda { |product| { :conditions => { :product_id => product.id }, :order => 'created_at DESC', :limit => 1 } }
end

Then to get the current pricing of a product, you'd call "Pricing.current(product).first".

In addition to the named scope on pricing, you could add an accessor method to the Product model like so:

class Product < ActiveRecord::Base
  def current_pricing
    Pricing.current(self).first
  end
end


You're looking for a named_scope.Define this in your Pricing model.Supply it with 1 parameter, the product_id.

named_scope :latest_price, lambda { |*args| {:conditions => {:product_id => args.first}, :order => "created_at DESC", :limit => 1} }

Excellent screencast on this by the way.


Add a :limit to the query?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜