在build_association上获取未定义的方法以获得多态has_one关联

时间:2014-05-01 22:01:07

标签: ruby-on-rails polymorphic-associations has-one

我是新手,这个问题非常令人沮丧,但毫无疑问,有经验的人会很快看到这个问题。

我从CompaniesController获取一个未定义的方法`build_address'。我与Company的PostalAddress有一个多态的has_one关系。作为注册表单的一部分,我试图在CompaniesController新方法中创建新的公司和关联的地址对象。我正在使用正确的语法来构建has_one。

模型

class Company < ActiveRecord::Base  
  has_one :postaladdress, as: :address, dependent: :destroy
  accepts_nested_attributes_for :postaladdress
end

class PostalAddress < ActiveRecord::Base 
  belongs_to :address, polymorphic: true
end

控制器

class CompaniesController < ApplicationController
  def new
     @company = Company.new
     @address = @company.build_address
  end
end

迁移

class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.string :name
      t.string :subdomain

      t.timestamps
    end
  end
end

class CreatePostalAddresses < ActiveRecord::Migration
  def change
    create_table :postal_addresses do |t|
      t.string :addressline1
      t.string :addressline2
      t.string :addressline3
      t.string :town
      t.string :county
      t.string :postcode
      t.string :country

      t.references :address, polymorphic: true;

      t.timestamps
    end
  end
end

routes.rb中的嵌套资源

resources :companies do 
  resources :postaladdresses :except => :destroy
end

1 个答案:

答案 0 :(得分:4)

由于您在has_oneCompany之间设置了PostalAddress关联,因此您需要使用

@address = @company.build_postal_address

<强>更新

Company中的关联应如下所示:

has_one :postal_address, as: :address, dependent: :destroy

使用postal_address而非postaladdress,因为您的模型名称为PostalAddress而不是Postaladdress

注意:

仅供参考,如果你有has_many关联,那么它就是:

@address = @company.postal_address.build

有关其他详细信息,请参阅 Auto-generated methods for Associations