如何在一个表单中接受两个模型的属性?

时间:2015-01-16 05:38:48

标签: ruby-on-rails

我是一个Rails新手试图通过模型Vault'new'形式接受模型Address的嵌套属性,但我得到一个未定义的方法`build'为nil:NilClass ERROR

我有两个模型,这里是一个Vault模型:

class Vault < ActiveRecord::Base
  has_one :address, dependent: :destroy

  accepts_nested_attributes_for :address, allow_destroy: true
end

我在这里也有一个地址模型:

class Address < ActiveRecord::Base
  belongs_to :vault
end

这是我的Vault_controller'新'方法:

  def new
    @vault = Vault.new
    @vault.address.build
  end

这是我的_form.html.erb Vault partial的一部分,我试图捕获地址模型的信息:

 <%= f.fields_for :address do |builder| %>
    <%= builder.label :stnumber, "St. Number" %></br>
    <%= builder.text_field :stnumber %>
 <% end %>

1 个答案:

答案 0 :(得分:0)

 #vault.rb
class Vault < ActiveRecord::Base
  has_one :address, dependent: :destroy
  #Other codes goes here
end

 #address.rb
class Address < ActiveRecord::Base 
  belongs_to :vault
  #other code goes here.
end

构建地址(取决于关联)

 v = Vault.new 
 address = v.address.build 
 # this one will work only for has_many association.

 address = v.build_address 
 #this one will work for your has_one association

请检查this link.