views:

92

answers:

1

given the fact that a user has many credit cards and a credit card has many addresses, I am trying to create a form that creates a user and credit card with address all at once

relavent model code:

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

controller code

def new
  @user = User.new
  @user.credit_cards.build
end

view code

=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

So the problem I am having is that the address fields do not show up. I tried adding @user.credit_cards.addresses.build to the controller but I get a undefined method 'build' for nil error.

+2  A: 

In your controller, you should try:

cc = @user.credit_cards.build
cc.adrresses.build

or

@user.credit_cards.build
@user.credit_cards.each{|cc| cc.addresses.build }

@user.credit_cards.addresses.build doesn't work because @user.credit_cards returns an array…

Yannis
perfect, thanks for the quick reponse!
Russ Bradberry
I've just corrected a mistake I made, it's @[email protected]_cards.each{|cc| cc.addresses.build } and not @user.credit_cards @user.credit_cards.each{|cc| cc.addresses.build }
Yannis