轨。反向多态关联

时间:2015-01-28 21:37:54

标签: ruby-on-rails

我试图了解Rails中的反向多态关联。 我跟着this guide,但是我收到了一个错误。当我写some_type_object.clubs时效果很好,但是当我尝试some_club_object.type时出现错误:

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :type_elements in model Club

如何解决?

这是我的模特:

class Club < ActiveRecord::Base
  has_one :type_element, as: :element
  has_one :type, through: :type_elements
end

class Event < ActiveRecord::Base
  has_one :type_element, as: :element
  has_one :type, through: :type_elements
end

class Type < ActiveRecord::Base
  has_many :type_elements
  has_many :clubs, through: :type_elements, source: :element, source_type: 'Club'
  has_many :events, through: :type_elements, source: :element, source_type: 'Event'
end

class TypeElement < ActiveRecord::Base
  belongs_to :type
  belongs_to :element, polymorphic: true
end

我的迁移:

class CreateClubs < ActiveRecord::Migration
  def change
    create_table :clubs do |t|
      t.string :name
      t.belongs_to :type
      t.timestamps null: false
    end
  end
end

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :name
      t.belongs_to :type
      t.timestamps null: false
    end
  end
end

class CreateTypeElements < ActiveRecord::Migration
  def change
    create_table :type_elements do |t|
      t.belongs_to :type, index: true
      t.integer :element_id
      t.string :element_type

      t.timestamps null: false
    end
    add_foreign_key :type_elements, :types
    add_foreign_key :type_elements, :elements
  end
end

class CreateTypes < ActiveRecord::Migration
  def change
    create_table :types do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end

2 个答案:

答案 0 :(得分:2)

试试这个:

class Club < ActiveRecord::Base
  has_one :type_element, as: :element
  has_one :type, through: :type_element # <- change
end

我认为你应该把Type作为一个类。除非你真的想要STI,否则你不应该把它作为一个领域。

答案 1 :(得分:0)

您永远不应该有一个名为type的迁移列。它是一个ruby / rails保留字,如果你有一个名字,会导致麻烦。我相信模型名称也是如此,但不是100%。将任何名称从type更改为其他名称,这些错误将消失。