gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:05:20 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com