No such column with a belongs_to class_name relationship

故事扮演 提交于 2019-12-13 03:48:03

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/16929802/no-such-column-with-a-belongs-to-class-name-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!