views:

198

answers:

1

I have problem with STI and relationship in ActiveRecord. I think I missed something in the class methods, but I don't know for sure. Below is my models:

class User < ActiveRecord::Base
  has_many :advertisements
end

class Advertisement < ActiveRecord::Base
  belongs_to :user
end

class FreeAdvertisement < Advertisement
end

class PaidAdvertisement < Advertisement
end

Now I want to find all FreeAdvertisement under certain user, e.g:

u = User.find_by_username('myself')
@freebies = u.free_advertisements.all

It gives error:

undefined method `free_advertisements' for #<User:0x2360f18>

I can hack it by using u.advertisements.find :all, :conditions, but that's not that I want to do. Please help me to solve this problem. Thanks in advance.

+1  A: 

I think what you want is:

class User < ActiveRecord::Base
  has_many :free_advertisements
  has_many :paid_advertisements
end
Gabe Hollombe
It works. It seems that I have to add the whole sub-objects into the relationship. Thanks.
rails_newbie