我有一个有三种型号的rails应用程序:帐户,包裹和交付。我在交货时使用AR :: Relation范围来查找最近的交货和退货。帐户模型还需要查找最近交付的帐户。 我可以通过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
答案 0 :(得分:0)
我相信这样的事情会起作用
scope :recent_deliveries, joins(:deliveries).merge(Delivery.recent)
或者你可能需要使用范围
scope :recent_deliveries, scoped.joins(:deliveries).merge(Delivery.recent)
应该让你入门。