Ruby on Rails Wednesday, September 28, 2011


On Sep 28, 2011, at 3:28 PM, ERB wrote:

I have two models, users and companies as indicated below.  The users
table has a foreign_key "company_id".

class User < ActiveRecord::Base
    has_many :companies
end

class Company < ActiveRecord::Base
   belongs_to: user


this should be

belong_to :user




end

In my controller:

@user = User.where(:id => params[:id]).includes(:companies)

I get the following error:
SQlite3::SQLException: no such column: companies.user_id: SELECT
"companies".* FROM "companies" WHERE "companies"."user_id" IN ('8')




Did you create a migration and run rake db:migrate ?




Why is RAILS getting the foreign key wrong and why is it trying to
pull columns in the users table into the companies model?

--


Because you used .includes it is trying to eager load the companies. If you don't know what eager loading is, you don't need it right now. One day you will learn what eager loading is and you will then learn to use it, but until that day you can get by without it.

If you do know what eager loading is and your intention was to use it here, that's a different matter.






No comments:

Post a Comment