在 ActiveRecord 中帮助查找并包含条件

发布于 2024-09-14 12:03:38 字数 440 浏览 7 评论 0原文

我有一个Coach模型:

has_many :qualifications

我想找到所有attribute_idnil并且他们有一些资格的教练>。类似的东西。

def requirement
    legal_coaches = []
    coaches = find_all_by_attribute_id(nil)
    coaches.each do |coach|
        legal_coaches << coach if coach.qualifications.any?
    end
    legal_coaches
end

有没有一种方法可以将所有此类记录放在一行中?

I have a Coach Model which:

has_many :qualifications

I want to find all coaches whose some attribute_id is nil and they have some qualifications. Something which is like.

def requirement
    legal_coaches = []
    coaches = find_all_by_attribute_id(nil)
    coaches.each do |coach|
        legal_coaches << coach if coach.qualifications.any?
    end
    legal_coaches
end

Is there a way to get all such records in one line ?

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

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

发布评论

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

评论(2

Saygoodbye 2024-09-21 12:03:38
find_all_by_attribute_id(nil).select(&:qualification) 
find_all_by_attribute_id(nil).select(&:qualification) 
肩上的翅膀 2024-09-21 12:03:38

我认为你不能通过纯粹的 ruby​​ 语法来做到这一点。我只能想到以下(丑陋的)方式

Coach.find(:all, :conditions => "attribute_id IS NULL AND EXISTS(SELECT * FROM qualifications WHERE coach_id = coaches.id)")

I think you can't do that via purely ruby syntax. I can only think of the following (ugly) way

Coach.find(:all, :conditions => "attribute_id IS NULL AND EXISTS(SELECT * FROM qualifications WHERE coach_id = coaches.id)")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文