Ruby on Rails Wednesday, September 28, 2011

On Sep 28, 2011, at 12: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
> 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')
>
>
> Why is RAILS getting the foreign key wrong and why is it trying to
> pull columns in the users table into the companies model?
----
class Company < AR::B
belongs_to :user

that's why

also, if
class User < AR::B
has_many :companies

then having a column named users.company_id is a waste of time and space too.

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Craig

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment