【发布时间】:2013-07-27 17:55:42
【问题描述】:
我的 Rails 应用程序中有两个实体,我正在尝试建立关系 - 检查和月份。 Month 的实例将具有 start_date 和 end_date - 这些日期与日历月不完全一致。 Check 的实例将有一个 deposit_date。我想以某种方式描述一种关系,其中月份有很多支票,存款日期在月份的开始日期和结束日期之间。这可能吗?
【问题讨论】:
我的 Rails 应用程序中有两个实体,我正在尝试建立关系 - 检查和月份。 Month 的实例将具有 start_date 和 end_date - 这些日期与日历月不完全一致。 Check 的实例将有一个 deposit_date。我想以某种方式描述一种关系,其中月份有很多支票,存款日期在月份的开始日期和结束日期之间。这可能吗?
【问题讨论】:
这是可能的。您可以自定义您的 relation
参考。
class Month < ActiveRecord::Base
has_many :checks, ->(month) { where deposited_at: (month.start_at)..(month.end_at) }, class_name: 'Check'
end
您实际上不需要指定class_name
,除非您更改关系名称。例如,如果您使用 current_checks
而不是简单地命名为 checks
。
【讨论】:
我最后做的是从 Month 类中删除 has_many :checks,并定义了我自己的方法:
class Month < ActiveRecord::Base
# other associations and validations omitted
def checks
Check.where(deposit_date: self.start_date..self.end_date)
end
end
我不知道这是否会被视为 hack,但它给了我我需要的东西。当然,我愿意看到更多的“Rails 方式”来做到这一点。
【讨论】: