3
中使用多個「一對多」嵌套屬性,因爲用戶有很多信用卡,信用卡上有很多地址,我試圖創建一個表單來創建用戶和信用額度卡地址一次全部如何在form_for
relavent型號代碼:
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
錯誤。
完美,感謝您的快速效應初探! – 2010-09-16 12:45:32
我剛糾正了我犯的一個錯誤,它是@ user.credit_cards.build @ user.credit_cards.each {| cc | cc.addresses.build}而不是@ user.credit_cards @ user.credit_cards.each {| cc | cc.addresses.build} – Yannis 2010-09-16 12:48:56