2013-04-18 29 views
0

我目前正在建模一個Rails 3.2應用程序,並且需要名爲「archives」的表中名爲「archivable」的多態關聯。不用擔心,但我的「檔案」表也必須屬於「連接」表。我只想知道Rails是否有任何限制來做到這一點。具有其他種類關聯的Rails多態表

You can see the model here

另一個細節,我的連接模式已經兩次user_id說明爲外鍵。作爲發件人的user_id和作爲收件人的user_is。可能?我認爲我下面做的事情是行不通的...

這是我的模特協會。

class User < ActiveRecord::Base 
    has_many :connections, :foreign_key => :sender 
    has_many :connections, :foreign_key => :receiver 
end 

class Connections < ActiveRecord::Base 
    belongs_to :user 
    has_many :archives 
end 

class Archive < ActiveRecord::Base 
    belongs_to :connection 
    belongs_to :archivable, :polymorphic => true 
end 

class Wink < ActiveRecord::Base 
    has_many :archives, :as => :archivable 
end 

class Game < ActiveRecord::Base 
    has_many :archives, :as => :archivable 
end 

class Message < ActiveRecord::Base 
    has_many :archives, :as => :archivable 
end 

您是否發現任何錯誤或者某些不適用於Rails的內容?

謝謝你們。

回答

1

我想你想這樣做:

class Connections 
    belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id' 
    belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id' 
end 

class User 
    has_many :sended_connections, :class_name => 'Connection', :as => :sender 
    has_many :received_connections, :class_name => 'Connection', :as => :receiver 
end 

重要:不要聲明2倍的has_many:具有相同名稱的連接!

+0

謝謝隊友。而關於我想要的多態關聯,不用擔心這個設計? – Gozup

+0

這對我來說似乎沒問題。 – pierallard

+1

有點補充:而不是'User.to_s'和'Connection.to_s'我分別使用「用戶」和「連接」。原因是,通過使用類常量,您可以強制rails/activesupport立即要求另一個模型,這可能會導致循環依賴。 –