views:

159

answers:

3

I am using single table inheritance in my project. Instead of explaining more, I'll give the code:

# person_profile.rb
class PersonProfile < ActiveRecord::Base
  belongs_to :Person
end

# company_profile.rb
class CompanyProfile < ActiveRecord::Base
  belongs_to :Company
end

# person.rb
class Person < User
  has_one :PersonProfile
end

# company.rb
class Company < User
  has_one :CompanyProfile
end

This seems to me like it should work fine. In one of my views I try if @person.PersonProfile == nil which makes perfect sense to me. But Rails doesn't like it:

 Mysql::Error: Unknown column 'person_profiles.person_id' in 'where clause': SELECT * FROM `person_profiles` WHERE (`person_profiles`.person_id = 41)  LIMIT 1

Rails is looking for person_id in the table person_profiles, but there is only a user_id in that table. What is the best way to fix this bug?

+2  A: 

The models specified in your model associations should be in lowercase with each word being separated by an underscore. So:

class PersonProfile < ActiveRecord::Base
  belongs_to :person
end

class CompanyProfile < ActiveRecord::Base
  belongs_to :company
end

class Person < User
  has_one :person_profile
end

class Company < User
  has_one :company_profile
end
John Topley
thats true, then i guess i would say `@person.person_profile == nil`. But that still doesnt fix the problem. I get the same mysql error.
Sam
A: 

i had to specify the foreign_key as 'user_id' because it thinks its 'person_id' by default.

class Person < User
   has_one :person_profile, :foreign_key => 'user_id'
end

class Company < User
   has_one :company_profile, :foreign_key => 'user_id'
end
Sam
+3  A: 

You can use the :foreign_key option of has_one to specify the key.

For example:

has_one :person, :foreign_key => "user_id"

See this reference.

Martin Gordon