OK so I've been at this for 6 plus hours and scoured every variation on this question, but nothing I do works!
I'm building a fairly simple family tree app for a friend. There are two models in question, Person and Relationship. Whenever you build a new Person (after the very first one which is handled separately), it should also build a Relationship which is essentially a join table that has a person_1 attribute, a person_2 attribute, and a relationship_type attribute such as "mother".
When I build a new person, that person is saved to the database just fine, but the associated relationship is not. I can see that all of the necessary params are being passed in, and I've read as much as I can about nested params, but no dice.
My code is a big old mess and I'm a beginner so please ignore any unrelated code weirdness.
My Person model (this centers around the out_relationships resource)
class Person < ApplicationRecord
has_many :out_relationships, :class_name => "Relationship", :foreign_key => "person_1_id"
has_many :in_relationships, :class_name => "Relationship", :foreign_key => "person_2_id"
belongs_to :user, optional: true
accepts_nested_attributes_for :out_relationships
end
My Relationship model:
class Relationship < ApplicationRecord
belongs_to :person_1, :class_name => "Person"
belongs_to :person_2, :class_name => "Person"
end
My form:
<%= form_for @person, :url => create_relative_path, html:{method:'post'} do |form| %>
<%= fields_for :out_relationships do |builder| %>
<div class="form-group">
<%= builder.label :relationship_type, "Relationship to #{@root_person.first_name}" %>
<%= builder.text_field :relationship_type, class: "form-control" %>
<%= builder.hidden_field :person_1, value: @person_1.id %>
<%= builder.hidden_field :person_2, value: @person_1.id %>
</div>
<% end %>
I set person_1 and person_2 to the same value just as a test. That's kind of unrelated to the problem, I think, and shouldn't affect what's happening. Anyways...
My controller:
def new
@root_person = Person.find(params[:id])
@person = Person.new
@user = current_user
@root_person.out_relationships.build
end
# GET /people/1/edit
def edit
end
def create
@root_person = Person.find(params[:id])
@person = Person.new(person_params)
@user = current_user
respond_to do |format|
if @person.save
format.html { redirect_to @person, notice: 'Person was successfully created.' }
format.json { render :show, status: :created, location: @person }
else
format.html { render :new }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
def person_params
params.require(:person).permit(:first_name, :middle_name, :last_name, :birth_date, :birth_city,
:birth_country, :current_city, :current_country, :profession, :maiden_name, :marital_status, :patel_type,
out_relationships_attributes: [:person_1, :person_2, :relationship_type])
end
Anyways, that's more of a mess than I even thought, thanks to anyone still reading, would love a nudge in the right direction!