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.
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
<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.