ruby-on-rails – Rails:创建子/父关系

我无法将孩子添加到给定的父母.视图有一个“添加子”链接,该链接传入当前Person对象.从这里开始,我被困住了.父对象和子对象都是Person对象.

而且,逻辑很差 – 它目前假定为父亲.

型号(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

查看(people / _form.html.erb):

<%= link_to "Add Child", {:controller => '/people', :action => :new, :parent_id => @person.id} %>

最佳答案 这里的问题是,现在,您实际上没有将father_id或mother_id传递给“创建”操作.

“new”动作设置了mother_id / father_id(使用构建)……但这只是意味着它可以放在页面上的表单中……然后你必须以某种方式将它传递回“创建”.

你形成的实际上是否包含一个名为“father_id”或“mother_id”的隐藏字段?

例如在模板中:

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

隐藏字段只会返回一个值(如果它已经设置好了)(例如你已经在控制器#new动作中执行了这个操作),如果它没有,它将正确地以nil的形式通过.

点赞