【发布时间】:2015-11-25 10:20:09
【问题描述】:
我有 4 个模型:Artists, Editions, Events & EventItems。
- 版本有很多事件
- 事件通过 EventItems 有很多艺术家
- 各版本通过活动有许多艺术家
关于艺术家我有一个范围published
我将活跃定义为参加活动的艺术家,其状态不是draft。
scope :published, -> { joins(:events).where("events.state != ?", 'draft').uniq }
这很好用,直到我开始链接它们并希望艺术家在给定版本中至少有 published 的事件。
Edition.first.artists.published
除了它还会加入当前版本之外的events,并且如果艺术家发布了任何事件(即使他们不在此特定版本中),则会错误地发布艺术家。
为了让它正常工作,我不得不像这样破解它(这太可怕了):
scope :published, ->(edition = nil) {
if edition.present?
joins(:events).where("events.state != ? AND events.edition_id = ?", 'draft', edition.id).uniq
else
joins(:events).where("events.state != ?", 'draft').uniq
end
}
Edition.first.artists.published(Edition.first)
是否有更多的上下文来说明这个版本中只包含这些事件的范围?那么它的范围会正确吗?
谢谢!
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-4.2 named-scope scopes