簡體   English   中英

has_many :through 關聯可以有其他關聯嗎?

[英]Can a has_many :through association have other associations?

has_many, through: assocation 連接模型是否有可能具有關聯? 假設有這個關聯,我有一個產品列表,其中有很多不同的價格,其中每個價格都與一個國家/地區相關聯。 因此,我可以獲取我的產品在其中可用的所有國家/地區或在一個國家/地區內可用的每個產品。

產品

has_many :prices
has_many :countries, through :prices

價格

belongs_to :product
belongs_to :country

國家

has_many :prices
has_many :products, through :prices

現在我想在我的價格模型上添加其他關聯,其中價格 has_one :currency,以及價格由該信息所屬的用戶定義的位置。 是否可以像這樣添加關聯?

價格

belongs_to :product
belongs_to :country

has_one :currency
belongs_to :user

我不知道一個簡單的“是”是否會幫助您解決問題,但是(因為您基本上已經提供了正確的代碼):是的。

您的prices連接模型是默認的 Rails 模型,因此您可以像對待其他模型一樣對待它(並實現關聯、回調、自定義查找器等)。 您只需要確保數據庫表中的外鍵正確排列(例如, prices需要一個user_id列)。

不是問題的一部分,而是一個小小的評論:

不過,我不確定您是否希望您的價格為has_one貨幣。 這意味着,外鍵是在currencies表( price_id ),這又意味着貨幣belongs_to價格(也許你而希望你的貨幣has_many的價格和你的價格也belongs_to貨幣)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM