quantumpotato
quantumpotato

Reputation: 9767

No such column with a belongs_to class_name relationship

SQLite3::SQLException: no such column: organizations.user_id: SELECT "organizations".* FROM "organizations" WHERE "organizations"."user_id" = 2

I have setup my models like this:

User:

User has_many :organizations

Organization:

attr_accessible :name, :founder, :founder_id
belongs_to :founder, :class_name => 'User'

Schema:

create_table "organizations", :force => true do |t|
t.string   "name"
t.integer  "founder_id"

When I go to edit a user in rails-admin, I get this message:

`SQLite3::SQLException: no such column: organizations.user_id: SELECT "organizations".* FROM "organizations"  WHERE "organizations"."user_id" = 2`

I want to access Founder on Organization, where a Founder is a User. It looks like rails_admin looks for the user_id when it should be looking for a Founder.

Previous q: Can access _id of a references object but not the object directly

Upvotes: 1

Views: 595

Answers (2)

leonhart
leonhart

Reputation: 1201

Organization model is belong to User, so rails will automatic use the User's lowercase class name +_id(user_id) as foreign_key. Since your Organization model doesn't have the user_id but the founder_id, you need to explicit specify the founder_id as foreign_key.

Upvotes: 0

DanneManne
DanneManne

Reputation: 21180

You need to specify which column to use when retrieving organizations from User, like this:

class User < ActiveRecord::Base
  has_many :organizations, foreign_key: :founder_id

  #...
end

Upvotes: 2

Related Questions