Tutorial :Rails Inheritance with relationships problem



Question:

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?


Solution:1

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.


Solution:2

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  


Solution:3

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  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »