JP.
JP.

Reputation: 5594

Ruby ActiveRecord has_one with conditions

Let's say I have some Items for sale, and I'm keeping track of their Cost historically:

class Cost < ActiveRecord::Base
  belongs_to :item

  # eg: costs.amount = 123.45; costs.item_id = 1; costs.created_at = 2011-08-11 16:28
end

class Item < ActiveRecord::Base
  has_many :costs

  # eg: items.id = 1; items.name = Cheese Sandwich
end

This code works, I can pull out all the previous costs for the item I'm selling.

I feel like it should be possible to have a second clause for Item so that I can pull out the current price directly:

class Item < ActiveRecord::Base
  has_many :costs
  has_one :current_cost, :class_name => :costs, :conditions => 'MAX(created_at)'
end

my_item.current_cost # => <£123.45, 45 minutes ago>

Any ideas how to achieve this?

Upvotes: 0

Views: 983

Answers (3)

yang
yang

Reputation: 508

has_one :current_cost, :class_name => :costs, :order => 'create_at DESC'

Upvotes: 2

Sector
Sector

Reputation: 1210

You can use the scope:

class Item < ActiveRecord::Base
  has_many :costs
  scope :current_cost, limit(1).order("created_at DESC")
end

usage:

my_item.current_cost

Upvotes: 0

fl00r
fl00r

Reputation: 83680

class Item < ActiveRecord::Base
  has_many :costs
  def current_cost
    self.costs.order("created_at DESC").first
  end
end

my_item.current_cost

Upvotes: 4

Related Questions