【问题标题】:How do I use multiple "one-to-many" nested attributes in form_for如何在 form_for 中使用多个“一对多”嵌套属性
【发布时间】:2010-09-16 12:30:41
【问题描述】:

鉴于一个用户有很多信用卡并且一张信用卡有很多地址,我正在尝试创建一个表单来同时创建一个用户和信用卡的地址

相关型号代码:

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

【问题讨论】:

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


    【解决方案1】:

    在您的控制器中,您应该尝试:

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

    【讨论】:

    • 我刚刚纠正了我犯的一个错误,它是@user.credit_cards.build @user.credit_cards.each{|cc| cc.addresses.build } 而不是 @user.credit_cards @user.credit_cards.each{|cc| cc.addresses.build }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多