ruby-on-rails - 通过关系表 Rails 一对多

标签 ruby-on-rails postgresql activerecord

我有一家通过连接表 company_user 拥有许多用户的公司。每个用户应该只为一家公司工作。这是一对多的关系。

我四处寻找并在 https://stackoverflow.com/a/7080017/883102 中找到了解决方案

但是我得到了错误

PG::UndefinedTable: ERROR: relation "companies" does not exist LINE 5: WHERE a.attrelid = '"companies"'::regclass

当我尝试创建公司时。我该如何解决这个问题?

我的模型是

公司

class Company < ActiveRecord::Base
  has_many :employments
  has_many :users, :through => :employments
end

用户

class User < ActiveRecord::Base
  ...
end

就业

class Employment < ActiveRecord::Base
  belongs_to :company
  belongs_to :user
end

我的连接表的迁移是

create_table :employment do |t|
    t.belongs_to :company
    t.belongs_to :user
    t.timestamps
end

我的架构.rb

create_table "company", force: true do |t|
  t.integer  "rating"
  t.integer  "phone"
  t.string   "name"
  t.string   "address"
  t.string   "email"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "employment", id: false, force: true do |t|
  t.integer  "company_id"
  t.integer  "user_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "users", force: true do |t|
  t.string   "name"
  t.string   "email"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "password_digest"
  t.string   "remember_token"
  t.string   "role"
end

最佳答案

嗨,我在这里找到了答案 https://stackoverflow.com/a/24318236/883102

问题是我的表名是单数形式,我在迁移中更改了这些,然后重新创建了数据库。现在一切似乎都运行良好。

我的用户类最终为

class User < ActiveRecord::Base
  has_one :employment
  has_one :company, :through => :employment
end

这是为了允许双向关联

关于ruby-on-rails - 通过关系表 Rails 一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25025229/

相关文章:

ruby-on-rails - 使用 ElasticSearch + Tire 搜索多个术语

sql - PostgreSQL触发器和存储过程使用什么语言?

sql - Postgresql,创建了名为 'name' 的域名,如何删除它?

php - PostgreSQL 原始 SQL 插入 (Laravel 5.5)

sql - 是否存在关于 ActiveRecord 关系的困惑?方法,尤其是限制和偏移

ruby-on-rails - 在线 Rails 开发环境

ruby-on-rails - 自引用 has_many :through with customized :primary key issue

使用 ActiveRecord 进行 MySQL 分区

php - activerecord 作为模型,这是个好主意吗?

ruby-on-rails - Rails - 放置模型辅助方法的位置