1

This question is fairly similar to [1], except that I'm using Rails 2.3.5 (yes, old) and a complete newb at RoR. I have two models, Configfile and Signoff.

I want to find all Configfiles where the number of signoffs is < 2. Of course, I could do this by filtering the array manually, but this database is big and it's fairly slow.

class Configfile < ActiveRecord::Base
  belongs_to :computer
  has_many :signoffs,
           :dependent => :destroy
end

and

class Signoff < ActiveRecord::Base
  belongs_to :configfile
end

This seems like something that should be fairly easy to do in Rails, but I can't figure it out. My query looks like this so far, and I haven't gotten anything that works for limiting it by the number of signoffs.

configs = c.configfiles.find(:all,
                             :include => :signoffs,
                             :order => 'filename')

[1] Rails 3 query on condition of an association's count

1 Answer 1

2
Configfile.find(:all, :group=>"configfile_id", :joins=>:signoffs, :having=>"count(*) < 2")

Which should give you the same as the equivalent rails3:

Configfile.joins(:signoffs").group("configfiles.id").having("count_all < 2").count(:all)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! The final solution I got working was: configfiles.find(:all, :group=>"configfile_id", :joins=>:signoffs, :having=>"COUNT(*) < 2") (changing count_all to COUNT(*) and .count to .find)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.