Forum: Ruby on Rails Associate only include records with children?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
59ea1b450935b9d70abfec4186b7a4d5?d=identicon&s=25 Jeff Coleman (progressions)
on 2007-02-17 11:49
I'm building an application to view webcomics.  I've got three models,
User, Comic and Page.

I'd like to build an association in my User model that will return all
the Comic records which have 1 or more children Pages.

In my User model I have

class User < ActiveRecord::Base
  has_many :comics, :class_name => "Comic", :foreign_key =>
"created_by", :order => "last_updated DESC", :dependent => :destroy
  has_many :live_comics, :class_name => "Comic", :foreign_key =>
"created_by", :order => "last_updated DESC", :conditions => ["live = 1
AND published_on <= ?",]

Each comic has a publication date and a boolean "live" value.  Right
now, the association user.live_comics returns the set of Comic rows
where "live" is true and "published_on" is in the past.

I don't want "user.live_comics" to return Comics with 0 pages.  Is there
a way I can create an association to do that?

70225136eacd3d870f64e03bff678655?d=identicon&s=25 Russell Norris (Guest)
on 2007-02-17 15:28
(Received via mailing list)
I'm no associations expert so just because I don't see a solution of
kind doesn't mean there's not... That being said, what I would do [as
someone who doesn't see an easier fix] is write another method which
User#live_comics intermediarily [please, PLEASE, let that be a real
Something like...

def good_live_comics
  # Yay Enumerable methods!{|c| !}

I'd also have written the :conditions for that has_many :live_comics as
["live = ? and published_on <= ?", true,] since you've got a
boolean [true/false] on the database and not an integer [0/1]. But
probably more cosmetic than anything.

Hope I helped. Or at least made you chuckle at my pre-coffee insanity.

This topic is locked and can not be replied to.