Rails多态表,有其他种类的关联

时间:2013-04-18 10:22:36

标签: ruby-on-rails ruby activerecord ruby-on-rails-3.2

我目前正在为Rails 3.2应用程序建模,我需要一个名为“archives”的名为“archivable”的多态关联。不用担心,但我的“档案”表也必须属于“连接”表。我只是想知道Rails是否有任何约束来做到这一点。

You can see the model here

另一个细节,我的Connection模型有两次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 个答案:

答案 0 :(得分: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:具有相同名称的连接!