Rails 3 将相关模型加入其默认范围

发布于 2024-11-29 09:16:39 字数 597 浏览 1 评论 0原文

我正在尝试使用以下设置跨模型进行查询

Class Scorecard < AR::Base
  default_scope where(:archived => false)
  belongs_to :user
  has_many :scorecard_metrics
end

Class ScorecardMetric < AR::Base
  belongs_to :scorecard
end

Class User < AR::Base
  has_many :scorecards
end

我正在尝试使用连接记分卡的命名范围从记分卡指标进行查询,并且我希望它包含记分卡的默认范围,我当前的实现(有效)如下

# on ScorecardMetric
scope :for_user, lambda { 
  |user| joins(:scorecard).
         where("scorecards.user_id = ? and scorecards.archived = ?", user.id, false) 
}

所示对我来说似乎很混乱,有什么方法可以加入并包含加入关联的默认范围吗?

I'm trying to query across models with the following setup

Class Scorecard < AR::Base
  default_scope where(:archived => false)
  belongs_to :user
  has_many :scorecard_metrics
end

Class ScorecardMetric < AR::Base
  belongs_to :scorecard
end

Class User < AR::Base
  has_many :scorecards
end

I am trying to query from scorecard metrics with a named scope that joins scorecard and I want it to include the default scope for scorecard, my current implementation (which works) looks like this

# on ScorecardMetric
scope :for_user, lambda { 
  |user| joins(:scorecard).
         where("scorecards.user_id = ? and scorecards.archived = ?", user.id, false) 
}

This just seems messy to me, is there any way to join and include the default scope of the joined association?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒废 2024-12-06 09:16:39

看起来我找到了我正在寻找的答案,我刚刚这样做了,

scope :for_user, lambda { |user| joins(:scorecard).where('scorecards.user_id = ?', user.id) & Scorecard.scoped }

没有重复的逻辑就好多了

Looks like I found the answer I was looking for, I just did this

scope :for_user, lambda { |user| joins(:scorecard).where('scorecards.user_id = ?', user.id) & Scorecard.scoped }

which is much nicer without the duplicated logic

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文