我正在嘗試爲用戶創建一個應用程序,以創建他們自己或希望購買的手錶列表。我希望用戶能夠描述很多關於手錶的細節/屬性。我試圖創建一個父/子關聯,但不使用STI,因爲子模型有不同的數據,我不想在表中添加一堆空值。Rails Polymorphic Association的問題
我有4個表:
- 用戶
- 某些用戶屬性
- 手錶
- USER_ID
- 一束通用於所有的手錶的屬性,名稱,品牌等。
- 的content_id
- CONTENT_TYPE
- mechanical_watches
- 某些屬性僅適用於機械錶
- quartz_watches
- 一些屬性只適用於石英手錶 種
模式
class User < ApplicationRecord
include Clearance::User
has_many :watches
end
class Watch < ApplicationRecord
belongs_to :user
belongs_to :content, polymorphic: true
end
class MechanicalWatch < Watch
has_one :watch, as: :content
end
class QuartzWatch < Watch
has_one :watch, as: :content
end
我不是100%肯定,如果我正確地已經設置的關聯。但是我遇到的問題是,當我將MechanicalWatch輸入到控制檯時,它僅返回Watch上的屬性而不返回mechanical_watches表中的任何屬性。我試過了我能想到的一切。任何想法,我做錯了什麼。
我使用的是Rails 5,Ruby 2.3.1和Postgres for db。
好的,那種感覺很有意義。也許'MechanicalWatch'不應該有'Watch'? 'MechanicalWatch'是一種'Watch'。無論哪種方式,我更改爲'class QuartzWatch
Ben
這聽起來正確的基礎上,你有它的方式設置。由於belongs_to在Watch上,因此MechanicalWatch的外鍵存儲在Watch上。 MechanicalWatch可能沒有直接存儲的字段。它只是提及Watch。 – kcdragon