我有一个简单的多对多E-R描述如下:
模型order.rb:
class Order < ActiveRecord::Base
has_many :cronologies
has_many :statuses, :through => :cronologies
end
Model cronology.rb:
class Cronology < ActiveRecord::Base
belongs_to :order
belongs_to :status
validates_uniqueness_of :order_id, :scope => :status_id
end
Model status.rb:
class Status < ActiveRecord::Base
has_many :cronologies
has_many :orders, :through => :cronologies
end
以下代码可让我获取分配给订单的所有状态。
@order.statuses
...但是如何通过cronology表的“created_at”属性获取状态?
答案 0 :(得分:5)
@order.statuses.all(:order => "cronologies.created_at")
如果您总是希望以这种方式订购,请将其关联起来。
class Order < ActiveRecord::Base
has_many :cronologies
has_many :statuses, :through => :cronologies, :order => "cronologies.created_at"
end