Associate only include records with children?

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 <= ?”, Time.now]
end

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?

Thanks,
Jeff

I’m no associations expert so just because I don’t see a solution of
that
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
calls
User#live_comics intermediarily [please, PLEASE, let that be a real
word].
Something like…

def good_live_comics

Yay Enumerable methods!

live_comics.select{|c| !c.pages.zero?}
end

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

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

RSL

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs