Rails Polymorphic has_one抛出未初始化的常量

时间:2014-08-20 03:09:30

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

在Rails 4中,我试图建立一个多态关系,其中我有一个地址模型,而其他多个模型将有一个地址。我有以下代码:

class Address < ActiveRecord::Base
    belongs_to :addressable, polymorphic: true
end

class Corporate < ActiveRecord::Base
    has_one :addressable

    accepts_nested_attributes_for :addressable
end

在我的数据库中,我有以下内容:

  create_table "addresses", force: true do |t|
    t.string   "line1"
    t.string   "line2"
    t.string   "city"
    t.string   "zip_code"
    t.string   "contact_person"
    t.string   "contact_number"
    t.integer  "addressable_id"
    t.string   "addressable_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "corporates", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
  end

但是,当我这样做时

@corporate = Corporate.new
@corporate.build_addressable

我收到以下错误:

NameError (uninitialized constant Corporate::Addressable)

知道问题是什么。我按照导轨指南,其中有一个has_many示例,而我使用has_one。

1 个答案:

答案 0 :(得分:3)

可能应该是:

class Corporate < ActiveRecord::Base
  has_one :address, as: :addressable
end