0

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.

1 Answer 1

1

You need to build the associated records

def new
  @abonent = Abonent.new
  @abonent.numbers.build
end
Sign up to request clarification or add additional context in comments.

3 Comments

Added @abonent.numbers.build right now. Nothing changed at all.
@OmBird also try changing <%= form_for :abonents, url: abonents_path do |f| %> to <%= form_for @abonent do |f| %>
i changed this. And after that rails showed me an error param is missing or the value is empty: abonents. I searched this error and changed params.require(:abonents).permit( :fullname, :work_position, :department, :email, :town_id, numbers_attributes: [:id, :phone] ) to params.require(:abonent).permit( :fullname, :work_position, :department, :email, :town_id, numbers_attributes: [:id, :phone] ). And it worked! Thanks a lot! You are my hero =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.