Trouble with :include

For some reason it seems that :include is not working for a couple of
my associations. Here are the models I’m using:

MODELS

class Registration < ActiveRecord::Base
has_many :events, :foreign_key => :user_id
end

Note the single table inheritance

class User < Registration
end

class Event < ActiveRecord::Base
belongs_to :user
has_one :image, :as => :imageable, :dependent => :destroy
end

class Image < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end

I’m using single table inheritance with Registrations because there
are 2 types of users on the site: User and TmpUser. A TmpUser is
essentially a shell that should not have any validation when saved and
a different set of filters.

When I run the following code it does not load either the image or
user association in the query:

evts = Event.find(:all, :include => [:image, :user], :conditions =>
“start IS NOT NULL AND start >= CURDATE()”)

So it runs a new query for each of these statements:

evts.first.image
evts.first.user

What am I doing wrong?

Thanks,
Jeremy

Does the Users table have a column named “type”? that is required for
STI

Yes the Registrations table has a column named “type”. Since Users
inherits from Registrations we don’t need a Users table (right?).

Thanks,
Jeremy

Correct, I wasn’t thinking far enough up the chain.

Does anybody know why I’m having this problem?

My guess is that Rails is lost because the STI with non-standard fks
is confusing. It’s able to navigate things better once you have the
instance back. You might give Rails a little help if you have a
require ‘registration’ at the top of your event.rb. That should help
rails find the STI subclasses before you try your Event.find.

Have you checked the log after running the initial query to see if it
is trying to do the joins?

I think one implication of your model is that only Users get to have
Events (at least Rails might think so). Is that true?

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