之間的關係,我有
User
是has_one :profile
。難度構建一個父模型和多種多態性兒童模特我有
Profile
有一些屬性,每個配置文件將有共同點。我想要一些
Users
有任何Coach_profile
或Student_profile
的Sub_profile
。
我打算使用Profile
這些Sub_profiles
之間的多態性關係,允許每個User
有自己的基本Profile
然後有他們適當Sub_profile
。
這是我打結的地方。
我有一個具有挑戰性的時間搞清楚的belongs_to
,has_one :profile
,as: :sub_profile
polymorphic: true
和dependent: :destroy
方法都屬於。
在這一點上,理解如何構建這種類型的解決方案的人將能夠寫出關係 - 但我覺得我需要解釋我的(有缺陷的)推理,以便像我這樣做,以便有人能夠幫助我明白我爲什麼做錯了。
我的問題:
同樣重要的是要注意,以防萬一它是不是很明顯,那下面的代碼結構,不會導致根據需要(如上所述),實際工作代碼。我有這樣的錯誤:
> Coach_profile.create
RuntimeError: Circular dependency detected while autoloading constant Coach_profile
,並試圖像:
> user.profile.build_coach_profile
結果undefined method build_coach_profile for profile
背後的原因我的代碼:
我有我的代碼的方式現在建立,我不知道如何build_sub_profiles
或build_coach_profile
(作爲一個例子)beca使用我設計的方式,我的關係不允許這樣做。
- 我希望我的
Profiles
到belongs_to :sub_profile, polymorphic: true, dependent: :destroy
因爲我希望這是我的profile
表sub_profile_id
,所以我可以- 參考
profile.sub_profile
- 有不同類型的
sub_profiles
- 銷燬相關
sub_profiles
當profile
被銷燬
- 參考
- 我希望我的
sub_profiles
(coach
和student
配置文件)has_one :profile, as: :sub_profile
- 我
sub_profile
類型的,這樣兩者可以通過我的profile
表的sub_profile_id
和sub_profile_type
領域屬於profile
。
- 我
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile
end
profile.rb
# id :integer not null, primary key
# user_id :integer
# first_name :string(255) not null
# middle_name :string(255)
# last_name :string(255) not null
# phone_number :integer
# birth_date :date not null
# created_at :datetime
# updated_at :datetime
# sub_profile_id :integer
# sub_profile_type :string(255)
#
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :sub_profile, polymorphic: true, dependent: :destroy
validates_presence_of :first_name, :last_name, :birth_date
validates_length_of :phone_number, {is: 10 || 0}
end
coach_profile.rb
# id :integer not null, primary key
# coaching_since :date
# type_of_coach :string(255)
# bio :text
# created_at :datetime
# updated_at :datetime
#
class CoachProfile < ActiveRecord::Base
has_one :profile, as: :sub_profile
end
student_profile.rb
# id :integer not null, primary key
# playing_since :date
# competition_level :string(255)
# learn_best_by :string(255)
# desirable_coach_traits :text
# goals :text
# bio :text
# created_at :datetime
# updated_at :datetime
#
class StudentProfile < ActiveRecord::Base
has_one :profile, as: :sub_profile
end
我在這裏接近錯誤的東西。如何正確設置幾個sub_profiles
和父母profile
之間的多態關係?
只需在配置文件和子配置文件之間反轉belongs_to has_one,就可以在幾分鐘內找出其他所有內容。 –
我改變了我的子配置文件,以讀取'belongs_to:profile,polymorphic:true',而不是'has_one:profile,as :: sub_profile',並將'as :: sub_profile'部分移到配置文件中的has_one行,因爲它似乎我不能在'belongs_to'調用上使用'as::model'。 然後,我添加了'belongs_to:profile,作爲::sub_profile'到我的sub_profiles的遷移。 嘗試'Coach_profile.create'時,我仍然收到循環依賴錯誤,我想我仍然錯過了一些東西。如果你有任何意見,這將是偉大的,但我會繼續挖掘。 – Ecnalyr