Rails: create a child / parent relationship

I am having problems adding children to this parent. The view has a “Add Child” link, which runs in the current Person object. I'm stuck from here. Both the parent and the child are Person objects.

In addition, the logic is bad - she is currently accepting a father.

Model (person.rb):

class Person < ActiveRecord::Base has_many :children, :class_name => "Person" belongs_to :father, :class_name => "Person", :foreign_key => 'father_id' belongs_to :mother, :class_name => "Person", :foreign_key => 'mother_id' def children Person.find(:all, :conditions => ['father_id=? or mother_id=?', id, id]) end end 

Controller (people_controller.rb):

 class PeopleController < ApplicationController # GET /people/new # GET /people/new.xml def new if (params[:parent_id]) parent = Person.find(params[:parent_id]) @person = Person.new(:lastname => parent.lastname, :telephone => parent.telephone, :email => parent.email) @person.father.build(:father_id => parent.id) else # create new @person = Person.new end respond_to do |format| format.html # new.html.erb end end # POST /people # POST /people.xml def create @person = Person.new(params[:person]) respond_to do |format| if @person.save format.html { redirect_to(@person, :notice => 'Person was successfully created.') } else format.html { render :action => "new" } end end end end 

View (people / _form.html.erb):

 <%= link_to "Add Child", {:controller => '/people', :action => :new, :parent_id => @person.id} %> 
+4
source share
1 answer

The problem here is that right now you are not actually passing either father_id or mother_id to the "create" action.

The "new" action sets mother_id / father_id (using build) ... but that just means that it is placed there on the form on the page ... then you need to pass it in order to "create" somehow.

Do you create the actual content of, say, a hidden field called "father_id" or "mother_id" anywhere?

for example in a template:

 <% form_for(@person) do |f| %> <%= f.hidden_field :father_id %> <%= f.hidden_field :mother_id %> #everything else here <% end %> 

Hidden fields return a value only if it has already been set (for example, you already do this in ############################# ###############################################

+2
source

All Articles