OmBird
OmBird

Reputation: 3

Rails nested form creation

I have an app in which i want create nested form

my models:

class Abonent < ActiveRecord::Base
    belongs_to :town
    has_many :numbers, :dependent => :destroy

    accepts_nested_attributes_for :numbers
end

class Number < ActiveRecord::Base
    belongs_to :abonent
end

Abonents controller:

class AbonentsController < ApplicationController


def new
    @abonent = Abonent.new
end

def create
    @abonent = Abonent.new abonents_params
    if @abonent.save
        redirect_to :towns
    else
        render action: "new"
    end
end

private 

 def abonents_params
    params.require(:abonents).permit( :fullname, :work_position, :department, :email, :town_id, numbers_attributes: [ :phone ] )
 end

end

And abonents view

<hr><br>

<%= form_for :abonents, url: abonents_path do |f| %>
  <%= f.label :fullname %>:
  <%= f.text_field :fullname %><br /> <br /> 

  <%= f.label :work_position %>:
  <%= f.text_field :work_position %><br /><br /> 

  <%= f.label :department %>:
  <%= f.text_field :department %><br /><br /> 

  <%= f.label :email %>:
  <%= f.text_field :email %><br /><br /> 

  <%= f.label :town_id %>:
  <%= f.select :town_id, Town.all.collect { |p| [ p.ru_name, p.id ] } %><br /><br /> 

  <%= f.fields_for :numbers do |phones|%>
    <%= phones.label :phone %>:
    <%= phones.text_field :phone %><br /><br /> 

  <% end %>


  <%= f.submit %>
<% end %>

The problem is when i submit form, it creates abonent, but doesn't create number for this abonent.

I saw many different manuals and couldn't find the error in my code. Please help. Thank you.

UPD I added a repo on github for this problem.

Upvotes: 0

Views: 55

Answers (1)

Pavan
Pavan

Reputation: 33552

You need to build the associated records

def new
  @abonent = Abonent.new
  @abonent.numbers.build
end

Upvotes: 1

Related Questions