Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Create child/parent relationship

I'm having trouble adding children to a given parent. The view has an "Add child" link that passes in the current Person object. From here, I'm stuck. Both the parent and child are Person objects.

Also, the logic is poor - it is currently assumes 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} %>
like image 355
theinein Avatar asked Nov 04 '22 20:11

theinein


1 Answers

The problem here is that right now, you don't actually pass either father_id or mother_id to the "create" action.

The "new" action sets up mother_id/father_id (using build)... but that just means it's there to put into the form on the page... you then have to pass it back to "create" somehow.

Does you form actually contain, say, a hidden field called "father_id" or "mother_id" anywhere?

eg in the template:

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

The hidden fields will only return a value if it's already been set (eg you already do this in the controller #new action) if it hasn't, it will correctly come through as nil anyway.

like image 157
Taryn East Avatar answered Nov 15 '22 06:11

Taryn East