如何在form_for中使用多个“一对多”嵌套属性

时间:2010-09-16 12:30:42

标签: ruby-on-rails ruby has-many nested-attributes form-for

鉴于用户拥有多张信用卡且信用卡上有许多地址这一事实,我正在尝试创建一个表单,用于创建一个用户和信用卡,地址全部一次

相关模型代码:

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错误。

1 个答案:

答案 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会返回一个数组...