我有一个三层模型关系定义如下:
class User < ActiveRecord::Base
has_many :orders
scope :with_key, ->(key) { joins(:orders).merge( Order.with_key(key) ) }
end
class Order < ActiveRecord::Base
belongs_to :user
has_many :tags
scope :with_key, ->(key) { joins(:tags).merge( Tag.with_key(key) ) }
end
class Tag < ActiveRecord::Base
belongs_to :order
attr_accessible :key
scope :with_key, ->(key) { where(key: key) }
end
基本上用户有很多订单,每个订单都有很多标签。标签包含key
字段。范围with_key
允许我合并链接多个连接以允许
User.with_key("some_key") #=> All users whose orders have a tag with "some_key" as key
然而,这不是我所需要的 如何查找最后订单标记的所有用户&#34; some_key&#34;作为关键?