双多态关联

时间:2012-04-03 08:33:53

标签: ruby-on-rails polymorphic-associations

我有双重多态关联,基本上我将把问题模型和VideoInterview模型与Bond模型联系起来。它们是以这种方式制作的:

债券迁移

class CreateBonds < ActiveRecord::Migration
  def change
    create_table :bonds do |t|
      t.references :sourceable, :polymorphic => true
      t.references :targetable, :polymorphic => true
      t.string :operation
      t.string :score
      t.timestamps
    end
  end
end

bond.rb

class Bond < ActiveRecord::Base
  belongs_to :sourceable, :polymorphic => true
  belongs_to :targetable, :polymorphic => true
end

question.rb

class Question < ActiveRecord::Base
  has_many :bonds, :as => :sourceable
  has_many :bonds, :as => :targetable
end

video_interview.rb

class VideoInterview < ActiveRecord::Base
  has_many :bonds, :as => :sourceable
  has_many :bonds, :as => :targetable
end

如何在订单中修改模型以正确使用此关联? 如果我打电话给@ question.bonds,我认为有一些错误,因为可源和可定位是在同一个has_many:bond下定义的。 我想制作@ question.sources并将所有与问题的关系作为可源元素。 谢谢

1 个答案:

答案 0 :(得分:1)

您需要为您的关联指定不同的名称,在可来源和可定位的情况下命名关联债券将不适合您。你可以将它命名为任何东西,并提供一个class_name来与问题模型

这样的债券模型相关联
class Question < ActiveRecord::Base
  has_many :sources, :class_name => 'Bond', :as => :sourceable
  has_many :targets, :class_name => 'Bond', :as => :targetable
end

,类似于VideoInterview模型

class VideoInterview < ActiveRecord::Base
  has_many :sources, :class_name => 'Bond', :as => :sourceable
  has_many :targets, :class_name => 'Bond', :as => :targetable
end

现在你可以调用这样的函数@ question.sources,@ question.targets,@ video_interview.sources,@ video_interview.targets

希望有所帮助。