3

ユーザーがたくさんのクレジットカードを持っていて、クレジットカードがたくさんのアドレスを持っているという事実を踏まえて、私はユーザーとアドレスを持つクレジットカードを一度に作成するフォームを作成しようとしています

関連するモデルコード:

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エラーが発生します。

4

1 に答える 1

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…</p>

于 2010-09-16T12:36:18.470 に答える