我有 3 個表(Freebie、Company、FreebieCompany),FreebieCompany 是中間表。2 個表(免費贈品,公司)使用has_many關聯并由中間表連接。我可以訪問公司表來獲取免費贈品,但不能訪問公司的贈品。
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 但沒有真正解決問題。我仔細檢查了遷移版本,所有表都列在架構中。
也許另一種觀點可以幫助我找到解決方案。每次我嘗試訪問這些公司時,都會出現以下錯誤。
> freebie.companies
* ``` ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: 關系“freebie_companies”不存在) LINE 1: ...ompanies"。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!
uj5u.com熱心網友回復:
看起來您的資料庫中沒有表示該關聯。最好查看您的架構以確保您的模型在您的資料庫中被正確參考。
通常在生成關聯模型時,我們運行:
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
在這里您可以找到有關has_many 的檔案:通過
uj5u.com熱心網友回復:
我忘了提到我使用多個資料庫。主資料庫和超級管理員資料庫。
這是我的新模型:
中介表:
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
隨時澄清并說出您的意見或疑慮,以使這一點變得更好。我希望這有幫助。謝謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507452.html
標籤:轨道上的红宝石
上一篇:忽略AWSRubySDK全域配置