[英]How to associate between 2 models which are not directly related in rails?
我有5個表格/模型。 這是結構。
1. application
id
name
2. profiles
id
name
app_id (Foreign key application table: id)
3. app_profiles
id
profile_id (Foreign key profile table: id)
app_id (Foreign key application table: id)
4. segments
id
app_id (Foreign key application table: id)
5. profile_segments
id
app_profile_id (Foreign key app_profile table: id)
segment_id (Foreign key segment table: id)
這是我的關聯:
application.rb
has_many :profiles, through: :app_profiles
has_many :segments
has_many :app_profiles
profile.rb
has_many :applications, through: :app_profiles
has_many :app_profiles
app_profile.rb
belongs_to :profile
belongs_to :application
has_many :segments, through: :profile_segments
has_many :profile_segments
segment.rb
has_many :profiles, through: :app_profiles
has_many :app_profiles, through: :profile_segments
has_many :profile_segments
belongs_to :application
profile_segment.rb
belongs_to :app_profile
belongs_to :segment
現在的問題是我需要在profile和profile_segment之間建立關聯。 能做到嗎? 如果可以,怎么辦?
在此先感謝您對我的幫助!
在profile.rb中添加:
has_many :profile_segments, through: :app_profiles
Rails has_many through:
語句支持鏈接的has_many through:
您的AppProfile
模型已經has_many :profile_segments
和Profile
has_many :app_profiles
,因此您可以將它們鏈接起來。
在后台,當您執行諸如profile.profile_segments
類的活動時, ActiveRecord
將執行2個INNER JOIN
。 您可以在rails server
的調試輸出中看到完整的SQL語句。 甚至我也不知道rails的魔力到底如何:D
我想說的是,我不知道您要達到什么目的,但是您的結構非常復雜。 嘗試刪除一些模型-可能將它們添加為其他模型中的某些列。
我必須這樣做以了解您的結構:
profile_segment
通過2條路徑屬於application
。 絕對不是一件好事。 也許它應該屬於profile
而不是app_profile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.