編輯:已更新的問題顯示我使用的:child_key => [:comparison_id]
正如評論中所建議的。如何在DataMapper中爲同一模型創建兩個多對多關係?
我有兩個模型,如下所示:
class Comparison
include DataMapper::Resource
property :id, Serial
end
class Msrun
include DataMapper::Resource
property :id, Serial
property :name, String
end
比較來自比較兩組Msruns的。我認爲我會通過比較到Msrun的兩個多對多關係來表示這種情況,但是我在DataMapper中如何做到這一點,正在打破我的觀點。我知道很多一對多的關係都可以通過添加這樣的事情:
has n, :whatevers, :through => Resource
然而,這樣只會讓兩個模型之間的一個多到多的關係。我也曾嘗試創建兩個連接模式和手動指定的關係,以及手工指定的,像這樣每個關係的子鍵:
# Join model for the comparison-msrun many-to-many relationship.
class First
include DataMapper::Resource
belongs_to :msrun, :key => true
belongs_to :comparison, :key => true
end
# Join model for the comparison-msrun many-to-many relationship.
class Second
include DataMapper::Resource
belongs_to :msrun, :key => true
belongs_to :comparison, :key => true
end
class Comparison
include DataMapper::Resource
property :id, Serial
has n, :firsts
has n, :msrun_firsts, 'Msrun', :through => :firsts, :child_key => [:msrun_id]
has n, :seconds
has n, :msruns_seconds, 'Msrun', :through => :seconds, :child_key => [:msrun_id]
end
class Msrun
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :firsts
has n, :comparison_firsts, 'Comparison', :through => :firsts, :child_key => [:comparison_id]
has n, :seconds
has n, :comparison_seconds, 'Comparison', :through => :seconds, :child_key => [:comparison_id]
end
運行automigrate
導致以下錯誤:
rake aborted!
No relationships named msrun_firsts or msrun_first in First
什麼時我在這裏做錯了嗎?我該如何做這項工作?
對不起,我應該說得更清楚。我已經嘗試過了,並且出現以下錯誤:第一個沒有名爲first_msruns或first_msrun的關係 – jergason
爲了避免命名錯誤,您必須爲Msrun指定'has n,:firsts,...:child_key => [:msrun_id]' ''和'具有n,:firsts,...:child_key => [:comparison_id]'用於'Comparison'。 ':child_key'需要綁定不同名稱的字段。 – ujifgc