Rails一表多个多态关系

时间:2014-11-13 21:25:12

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

我有一个表(连接),它需要有多个多态关系。第一个是工作,但第二个是错误。这是表格的布局。即使我将has_many :links, as: :linkable更改为has_many :connection_links, as: :linkable,我也会收到此错误,认为这是一些保留字。

class CreateConnections < ActiveRecord::Migration
  def change
    create_table :connections do |t|
      t.integer     :connectable_id
      t.string      :connectable_type
      t.integer     :linkable_id
      t.string      :linkable_type
      t.boolean     :status_id

      t.timestamps
    end
  end
end

class Connection < ActiveRecord::Base
  # relations
  belongs_to :connectable, polymorphic: true
  belongs_to :linkable, polymorphic: true
end


class Person < ActiveRecord::Base
  has_many :connections, as: :connectable, dependent: :destroy
  has_many :links, as: :linkable, dependent: :destroy
end

class Business < ActiveRecord::Base
  has_many :connections, as: :connectable, dependent: :destroy
  has_many :links, as: :linkable, dependent: :destroy
end

当我尝试将links错误拉出来时。

[2] pry(main)> person.connections Connection Load (0.4ms) SELECT "connections".* FROM "connections" WHERE "connections"."connectable_id" = $1 AND "connections"."connectable_type" = $2 [["connectable_id", 9], ["connectable_type", "Person"]] => []

[3] pry(main)> person.links NameError: uninitialized constant Person::Link

1 个答案:

答案 0 :(得分:2)

错误在于没有名为Link的课程 - 似乎没有你所展示的课程。