rails 4迁移一个人多个地址:ActiveRecord错误STI

时间:2015-11-12 17:17:06

标签: ruby-on-rails-4 activerecord

我有一个人模型,我想连接到多个地址(main_address,work_address等)

在app / models / person.rb中:

class Person < ActiveRecord::Base

  belongs_to :main_address, class_name: :Address, foreign_key: :main_address_id
  belongs_to :work_address, class_name: :Address, foreign_key: :work_address_id
  belongs_to :invoice_address, class_name: :Address, foreign_key: :invoice_address_id
  belongs_to :further_address, class_name: :Address, foreign_key: :further_address_id

end

地址模型:

class Address < ActiveRecord::Base
  belongs_to :person
end

地址迁移:

class CreateAddresses < ActiveRecord::Migration
  def change
    create_table :addresses do |t|
      t.string :street
      t.string :zip
      t.string :city
      t.string :country
      t.string :lockbox
      t.string :type
      t.references :person, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

应用程序/模型/ main_address.rb:

class MainAddress < Address
end

当我尝试在rails控制台中保存地址时(已创建id为1的人):

2.2.1 (main):0 > main_address = Address.create(type: "main_address", street: "Schumannstr.15", zip: "D-53113", city: "Bonn", country: "Germany", person_id: 1)

我收到错误:

ActiveRecord::SubclassNotFound: Invalid single-table inheritance type: main_address is not a subclass of Address

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为您的belongs_to关联可能存在问题。在我看来,一个地址属于一个人,一个人有很多地址。如果从概念上讲这并不代表您的要求,那么本答案的其余部分将需要进行调整。

此外,在原始示例中,您指定的地址表中的列不存在的外键。每个地址只能通过 id type 对引用。

我希望这种类型的代码可以工作:

# app/models/person.rb
class Person < ActiveRecord::Base 
    has_many :addresses 
end

# app/models/address.rb
class Address < ActiveRecord::Base 
    belongs_to :person     
end

# app/models/main_address.rb
class MainAddress < Address
end

表中的 type 列应触发STI,允许您执行以下操作:

person = Person.create(...)
person.addresses.create(street: "Schumannstr.15", zip: "D-53113", city: "Bonn", country: "Germany") 

希望这对你有用。如果没有,请随时根据需要进行编辑或评论。