ActiveRecord中的帮助查找包含条件

时间:2010-08-17 08:46:32

标签: ruby-on-rails activerecord find has-many

我有一个Coach模型:

has_many :qualifications

我想找到一些attribute_idnil并且有一些qualifications的教练。有点像。

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

有没有办法将所有这些记录放在一行?

2 个答案:

答案 0 :(得分:1)

find_all_by_attribute_id(nil).select(&:qualification) 

答案 1 :(得分:0)

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

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