我有一家通过连接表 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/