鉴于用户拥有多张信用卡且信用卡上有许多地址这一事实,我正在尝试创建一个表单,用于创建一个用户和信用卡,地址全部一次
相关模型代码:
class User < ActiveRecord::Base
has_many :credit_cards
accepts_nested_attributes_for :credit_cards
end
class CreditCard < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
控制器代码
def new
@user = User.new
@user.credit_cards.build
end
查看代码
=form_for @user, :url => users_path do |u|
=u.label :first_name, "Name"
=u.text_field :first_name
-u.fields_for :credit_cards do |cc|
=cc.label :name_on_card, "Name on Card"
=cc.text_field :name_on_card
-cc.fields_for :address do |address|
=address.label :address, "Address"
=address.text_field :address1
所以我遇到的问题是地址字段没有显示出来。我尝试将@user.credit_cards.addresses.build
添加到控制器,但出现undefined method 'build' for nil
错误。
答案 0 :(得分:5)
在您的控制器中,您应该尝试:
cc = @user.credit_cards.build
cc.adrresses.build
或
@user.credit_cards.build
@user.credit_cards.each{|cc| cc.addresses.build }
@user.credit_cards.addresses.build
不起作用,因为@user.credit_cards
会返回一个数组...