Iru*_*dji 1 activerecord many-to-many ruby-on-rails
我有一个简单的多对多ER描述如下:
型号order.rb:
class Order < ActiveRecord::Base
has_many :cronologies
has_many :statuses, :through => :cronologies
end
Run Code Online (Sandbox Code Playgroud)
型号cronology.rb:
class Cronology < ActiveRecord::Base
belongs_to :order
belongs_to :status
validates_uniqueness_of :order_id, :scope => :status_id
end
Run Code Online (Sandbox Code Playgroud)
型号status.rb:
class Status < ActiveRecord::Base
has_many :cronologies
has_many :orders, :through => :cronologies
end
Run Code Online (Sandbox Code Playgroud)
下面的代码让我获得分配给订单的所有状态.
@order.statuses
Run Code Online (Sandbox Code Playgroud)
...但是如何通过cronology表的"created_at"属性获取状态?
小智 5
@order.statuses.all(:order => "cronologies.created_at")
Run Code Online (Sandbox Code Playgroud)
如果您总是希望以这种方式订购,请将其关联起来.
class Order < ActiveRecord::Base
has_many :cronologies
has_many :statuses, :through => :cronologies, :order => "cronologies.created_at"
end
Run Code Online (Sandbox Code Playgroud)