我有一個名為 Company 的模型,該模型用于公司和客戶,我知道這不是公司/客戶的最佳方法,但我正在開發的軟體就是這樣構建的,要改變它,需要幾個月的時間的作業。
class Company < ActiveRecord::Base
has_many :companies
belongs_to :company
has_many :orders, dependent: :destroy
end
我的另一個模型是訂單,其中公司通過 company_id 列鏈接,客戶通過 customer_id 列鏈接,即訂單鏈接到公司和該公司的客戶。
class Order < ActiveRecord::Base
belongs_to :company
end
目前,我創建了一個獲取客戶的方法,但我想呼叫 has_one 從訂單中獲取客戶,但我無法使用 rails class_name將訂單的customer_id列指向公司id列。
uj5u.com熱心網友回復:
如果我正確理解了您的問題(在第一段中您提到了客戶,而在第二段中您說的是客戶,所以我假設客戶 == 客戶并且客戶也是一個Company物件)您正在嘗試這樣做:
class Order < ActiveRecord::Base
belongs_to :company
has_one :customer, class_name: 'Company'
end
這似乎是不正確的belongs_to:
class Order < ActiveRecord::Base
belongs_to :company
belongs_to :customer, class_name: 'Company'
end
這應該可以,但您也可以指定foreign_key:
belongs_to :customer, class_name: 'Company', foreign_key: :customer_id
來自檔案:https ://api.rubyonrails.org/v7.0.2.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one
has_one指定與另一個類的一對一關聯。僅當其他類包含外鍵時才應使用此方法。如果當前類包含外鍵,那么您應該改用belongs_to。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471109.html
上一篇:Rails:在表單上為我的collection_select下拉選單設定默認值時使用selected=>。但是當我編輯該專案時,它會默認回傳
