Jump to content

The ultimate community for Ruby on Rails developers.


Photo

nested form for a one-to-many (simple) relationship not working properly.

form one-to-many nestsed form

  • Please log in to reply
1 reply to this topic

#1 zhirzh

zhirzh

    Passenger

  • Members
  • 1 posts

Posted 17 August 2014 - 07:25 AM

Okay, so, let me start by saying that in RAILS 4, nested forms are a huge headache, when we go beyond one-to-one relationships.

Even after following many posts and videos, I still can't get it to work, so I finally turn up to the forum for some help.

 

I have 2 models - Father and Son. All I want to do is show the user a form, where he enters the name of father and his son and everything gets saved in the database, with the relationship,

The problem is that, even though father entry is saved, son entry is never.

 

 

Models

class Father < ActiveRecord::Base
  has_many :sons
  accepts_nested_attributes_for :sons
end


class Son < ActiveRecord::Base
  belongs_to :father
end

Here's the father controller

Father Controllerclass FathersController < ApplicationController
before_action :set_father, only: [:show, :edit, :update, :destroy]


def new
 @father = Father.new
 @father.sons.build
end


def create
 @father = Father.new(father_params)
 @father.save
 redirect_to @father,notice:'Father was successfully created.'
end


def index
 @fathers = Father.all
end

private
 def set_father
  @father = Father.find(params[:id])
 end

 def father_params
  params.require(:father).permit(:name,sons_attributes:[:name])
  end
 end

the  new-view

<h1>New father</h1>
<%= render 'form' %>

 

and the form

<%= form_for(@father) do |f| %>
  
  <div class="field">
    <%= f.label :name,"Father Name" %><br>
    <%= f.text_field :name %>
  </div>

  <%= f.fields_for :son do |s| %>
    <div class="field">
      <%= s.label :name, "Son Name" %><br>
      <%= s.text_field :name %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

If someone could just get it to work properly, I'd be more than happy.

 

 

 



#2 Jamie

Jamie

    Controller

  • Moderators
  • 140 posts
  • LocationNewcastle, UK

Posted 17 August 2014 - 01:28 PM

I recommend against using accepts_nested_attributes_for as it's a pain.

 

Take a look at point 3 for form objects, http://blog.codeclim...erecord-models/

 

However, try adding in :id to params.require(:father).permit(:name,sons_attributes:[:id, :name])

 

I'm not at my machine to replicate your issue at the moment.


  • FreightRunner likes this

Rails developer based in Newcastle, UK.






Also tagged with one or more of these keywords: form, one-to-many, nestsed form

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users