【问题标题】:ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation table does not exist)ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: 关系表不存在)
【发布时间】:2022-09-24 06:37:16
【问题描述】:

我有 3 张表(Freebie、Company、FreebieCompany),FreebieCompany 是中间表。 2张桌子(免费赠品,公司)使用有很多关联,并由中间表连接。我可以访问公司表以获取免费赠品,但不能访问公司的赠品。

class Company < ApplicationRecord
   has_many :freebie_companies
   has_many :freebies, through: :freebie_companies
end
class Freebie < ApplicationRecord
   has_many :freebie_companies
   has_many :companies, through: :freebie_companies
class FreebieCompany < ApplicationRecord
   belongs_to :freebie
   belongs_to :company
end

FreebieCompany 有 company_id 和 freebie_id。 我可以访问某个公司的赠品,但不能访问某个赠品的公司。

我确实 rake db:reset、drop、create、migrate、setup 和 db:schema:load 但没有真正解决问题。我仔细检查了迁移版本,所有表都列在架构中。

也许另一种观点可以帮助我找到解决方案。每次我尝试访问这些公司时,都会出现以下错误。

&gt; freebie.companies

*``` ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: 关系 \"freebie_companies\" 不存在) 第 1 行:...公司\"。FROM \"companies\" INNER JOIN \"freebi...


It\'s my first time to post here, and I\'ve been using my whole day to find the answer to this one.

Any help is very appreciated. Thank you so much!

    标签: ruby-on-rails


    【解决方案1】:

    看起来您的数据库中没有表示该关联。 最好查看您的架构以确保您的模型在您的数据库中被正确引用。

    通常在生成关联模型时,我们运行:

    rails g model FreebieCompany freebie:references company:references

    这将为 FreebieCompanies 表中的每个关联生成两列。

    t.bigint "freebie_id", null: false
    t.index ["freebie_id"], name: "index_freebie_companies_on_freebie_id
    t.bigint "company_id", null: false
    t.index ["company_id"], name: "index_freebie_companies_on_company_id
    

    Here 你可以找到关于has_many:通过

    【讨论】:

      【解决方案2】:

      我忘了提到我使用多个数据库。主数据库和超级管理员数据库。

      这是我的新模型:

      中介表:

      class FreebieCompany < SuperadminsRecord
       belongs_to :company
       belongs_to :freebie
      end
      

      主表:

      class Freebie < SuperadminsRecord
       has_many :freebie_companies
       has_many :companies, through: :freebie_companies
      end
      
      class Company < ApplicationRecord
       has_many :freebie_companies
       has_many :freebies, through: :freebie_companies
      end
      

      对于 inter 的迁移文件。桌子:

      class CreateFreebieCompanies < ActiveRecord::Migration[6.0]
       def change
        create_table :create_freebie_companies do |t|
         t.references :company, foreign_key: {to_table: :freebies}
         t.integer :freebie_id
      
         t.timestamps null: false
        end
       end
      end
      

      【讨论】:

        猜你喜欢
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 2022-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多