我有一个具有三个模型的 Rails 应用程序:帐户、包裹和交付。我在 Delivery 上使用 AR::Relation 范围来查找最近的交付和退货。Account 模型还需要查找最近交付的帐户。 我可以在 Account via 中使用相同的交付范围joins
吗? 现在我正在使用这样的代码(注意和中的重复Account.with_recent_returns
)Delivery.recent_returns
:
# Package(id: integer, ident: string)
class Package < ActiveRecord::Base
has_many :deliveries, :dependent => :destroy
end
# Delivery(id: integer, account_id: integer, delivered_on: date, package_id: integer, returned_on: date)`
class Delivery < ActiveRecord::Base
belongs_to :account
belongs_to :package
scope :current, where(:returned_on => nil)
scope :recent_deliveries, where('delivered_on >= ?', 2.weeks.ago)
scope :recent_returns, where('returned_on >= ?', 2.weeks.ago)
scope :returns, where('returned_on IS NOT NULL')
end
# => Account(id: integer, name: string)
class Account < ActiveRecord::Base
has_many :deliveries, :dependent => :destroy
def self.with_current_deliveries
joins(:deliveries).where(:deliveries => { :returned_on => nil } ).includes(:deliveries)
end
def self.with_recent_returns
joins(:deliveries).where('deliveries.returned_on >= ?', 2.weeks.ago).includes(:deliveries)
end
end