rails has_one和belongs_to错误

时间:2015-05-27 15:42:27

标签: ruby-on-rails ruby-on-rails-4 activerecord associations

我有一个用户模型和一个组织模型。 组织有一个用户,用户属于一个组织。

模式:

create_table "organizations", force: true do |t|
    t.string   "name"
    t.string   "org_name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end


class Organization < ActiveRecord::Base
  has_one :user
end

class User < ActiveRecord::Base
  belongs_to :user
end

当我在rails控制台中创建组织时,我收到以下错误(a = User.last)

»  Organization.create user_id: a.id, org_name: 'crap'
   (0.3ms)  BEGIN
  SQL (0.9ms)  INSERT INTO "organizations" ("created_at", "org_name", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id"  [["created_at", "2015-05-27 15:37:45.009037"], ["org_name", "crap"], ["updated_at", "2015-05-27 15:37:45.009037"], ["user_id", 42]]
   (1.3ms)  COMMIT
=> #<Organization:0x000001036de710> {
          :id => 8,
        :name => nil,
       :email => nil,
    :org_name => "crap",
  :created_at => Wed, 27 May 2015 16:37:45 BST +01:00,
  :updated_at => Wed, 27 May 2015 16:37:45 BST +01:00,
     :user_id => 42
}
[21] video »  Organization.last.user
  Organization Load (1.3ms)  SELECT  "organizations".* FROM "organizations"   ORDER BY "organizations"."id" DESC LIMIT 1
PG::UndefinedColumn: ERROR:  column users.organization_id does not exist
LINE 1: SELECT  "users".* FROM "users"  WHERE "users"."organization_...
                                              ^
: SELECT  "users".* FROM "users"  WHERE "users"."organization_id" = $1 LIMIT 1
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column users.organization_id does not exist
LINE 1: SELECT  "users".* FROM "users"  WHERE "users"."organization_...
                                              ^
: SELECT  "users".* FROM "users"  WHERE "users"."organization_id" = $1 LIMIT 1
from /Users/batman/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.4/lib/active_record/connection_adapters/postgresql_adapter.rb:869:in `prepare'
[22] video »  User.last.organization
  User Load (1.1ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" DESC LIMIT 1
=> nil

我不知道为什么协会不存在......!

1 个答案:

答案 0 :(得分:1)

我认为交换关联将解决您的问题。

class Organization < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :organization
end