STI Troubles in a has_many : belongs_to relationship

I’m having difficulty with single table inheritance when the STI table
is the “belongs_to” in a has_many / belongs_to relationship. Here’s
what the models look like (contrived and simplified) :

pie_lover.rb
class PieLover < ActiveRecord::Base
has_many :pies
end

pie.rb
class Pie < ActiveRecord::Base
belongs_to :pie_lover
end

cherry_pie.rb
class CherryPie < Pie
end

apple_pie.rb
class ApplePie < Pie
end

Can someone help me understand why:

This works:
CherryPie.count

And this works:
PieLover.find(:first).pies.count

But this fails:
PieLover.find(:first).cherry_pies.count

I tried adding “belongs_to :pie_lover” in cherry_pie.rb but it didn’t
make a difference. I’m guessing that I’m missing something simple.

Thanks for the guidance, folks!

  • Don

On Oct 11, 10:48 pm, Don S. [email protected]
wrote:

class Pie < ActiveRecord::Base

I tried adding “belongs_to :pie_lover” in cherry_pie.rb but it didn’t
make a difference. I’m guessing that I’m missing something simple.

Thanks for the guidance, folks!

  • Don


Posted viahttp://www.ruby-forum.com/.

If you want to find all pies, then
‘PieLover.find(:first).pies.count’

If you want just CherryPies, then PieLover has to ‘has_many
:cherry_pies’.

_Kevin

I tried adding “belongs_to :pie_lover” in cherry_pie.rb but it didn’t
make a difference. I’m guessing that I’m missing something simple.

OK, it was something simple. I didn’t add “has_many :cherry_pies” to
pie_lover.rb. Duh!

Since the STI section of the Agile Rails book doesn’t mention STI and
relationships, I assumed that you could get away with declaring the
relationship at the base of the object model. I didn’t realize that I
needed to declare each subclass explicitly. But since that’s how
everything else works… guess it’s time for a break!

Thanks!

If you want just CherryPies, then PieLover has to ‘has_many
:cherry_pies’.

Thanks Kevin! I did figured it out as you were typing. :wink:

Thanks!

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