[英]Using one form to create two models with overlapping attributes in Rails
[英]How to accept attributes for two models in one form?
我是一個Rails新手,試圖通過模型保管庫“新”表單接受模型地址的嵌套屬性,但是我為nil:NilClass錯誤獲取了一個未定義的方法“ build”
我有兩個模型,這里是一個保險庫模型:
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'new'方法:
def new
@vault = Vault.new
@vault.address.build
end
這是我_form.html.erb保管箱部分的一部分,在這里我試圖捕獲地址模型的信息:
<%= f.fields_for :address do |builder| %>
<%= builder.label :stnumber, "St. Number" %></br>
<%= builder.text_field :stnumber %>
<% end %>
#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
請檢查此鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.