ruby-on-railsfields-fornested-form-for

Rails 5 trouble with saving a nested fields_for .. error message <xxx> must exist


I have the following models:

class Person < ApplicationRecord
  has_many :interests, dependent: :destroy
  accepts_nested_attributes_for :interests

  validates_presence_of  :email
  validates_inclusion_of :gender, :in => %w(M F), message: "Gender can     only be in M or F"
  has_secure_password

  def name
    "#{first_name} #{last_name}"
  end

  def interests_concatenated
    interests.map { |i| i.interest }.join(", ")
  end
end

class Interest < ApplicationRecord
  belongs_to :person
end

My controller is as follows:

class PeopleController < ApplicationController

def index
  @person = Person.all
end

def new
  @person = Person.new
  @person.interests.build
end

def create
  @person = Person.new(people_params)
  if @person.save
    session[:user_id] = @person.id
    redirect_to(people_path)
  else
    flash = "Email or gender can't be blank!"
    render 'new'
  end
end

private
  def people_params
    params.require(:person).permit(:email, :first_name, :last_name, :gender, :password,:password_confirmation, interests_attributes: [:hobby])
  end
end

My form is as follows:

<%= form_for @person  do |f| %>
<p>
  <%= f.label :email %> <br>
  <%= f.text_field :email %>
</p>
<p>
  <%= f.label :first_name %> <br>
  <%= f.text_field :first_name %>
</p>
<p>
  <%= f.label :last_name %> <br>
  <%= f.text_field :last_name %>
</p>
<p>
  <%= f.label :gender %> <br>
  <%= f.label(:gender_male, "Male") %>
  <%= f.radio_button(:gender, "M") %> <br>
  <%= f.label(:gender_female, "Female") %>
  <%= f.radio_button(:gender, "F") %> <br>
</p>
<p>
  <%= f.label :password %> <br>
  <%= f.password_field :password %>
</p>
<p>
  <%= f.label :password_confirmation %> <br>
  <%= f.password_field :password_confirmation %>
</p>
<p>
  <%= f.fields_for :interests do |i| %>
    <%= i.label :hobby %>
    <%= i.text_field :hobby  %>
  <% end %>
</p>
<p>
  <%= f.submit %>
</p>
<% end %>

Here is the byebug console log when I run it:

console error message

Very stumped why it's not working. Could it be something to do with the parameters?

Here is the log file when I submit the form:

enter image description here


Solution

  • I found a working solution by adding this in my interests model:

    class Interest < ApplicationRecord
      belongs_to :person, **optional: true**
    end
    

    Since @person fails to save each time, the biggest clue was in the error message "Interest person must exist", I found this StackOverflow solution to be helpful. Also this blog post on why this is needed was helpful in shedding light on the issue.

    Thanks to everyone that weighed in on it!