How to use multiple nested one-to-many attributes in form_for

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

model reference 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 is that the address fields are not displayed. I tried adding @user.credit_cards.addresses.buildto the controller, but getting an error undefined method 'build' for nil.

+3
source share
1 answer

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 , @user.credit_cards ...

+5

Source: https://habr.com/ru/post/1765092/


All Articles