简体   繁体   中英

Ruby ActiveRecord has_one with conditions

Let's say I have some Item s 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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM