ruby-on-rails - 双重多态性关联

标签 ruby-on-rails polymorphic-associations

我有一个双重多态关联,基本上我将把问题模型和视频采访模型与邦德模型联系起来。它们是这样制作的:

债券迁移

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

债券.rb

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

问题.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 :bonds 下定义的。 我希望 ti make @question.sources 并获得与问题作为可来源元素的所有联系。 谢谢您

最佳答案

您需要为您的关联使用不同的名称,在可来源和可定位的情况下命名两个关联键将不适合您。您可以将其命名为任何名称,并提供一个 class_name 来与债券模型关联,就像问题模型一样

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

视频采访模型也类似

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

希望有帮助。

关于ruby-on-rails - 双重多态性关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9989761/

相关文章:

ruby-on-rails - 查找死轨代码

Mysql::错误:具有公共(public) Rails 关联的重复条目

ruby-on-rails - 如何生成迁移以使引用多态

ruby-on-rails - rails 4 : combining has_many :through association with polymorphic association

ruby-on-rails - 使用哪种测试方法? [ rails ]

ruby-on-rails - Rspec中的PG::InFailedSqlTransaction之后 Hook 中的错误

jquery - jquery-select2 的依赖下拉内容

ruby-on-rails-4 - Rails has_one 关联困惑

MySQL View : polymorphic associations and child tables

ruby-on-rails - libv8-3.16.14.3 安装失败 - Rails 4.1.8