嵌套表单未传递belongs_to:id

时间:2010-05-04 02:37:52

标签: ruby-on-rails nested-attributes

我有以下型号

class Project < ActiveRecord::Base
  has_many  :assignments, :conditions => {:deleted_at => nil}
  has_many  :members, :conditions => {:deleted_at => nil}
  accepts_nested_attributes_for :members, :allow_destroy => true
end

class Member < ActiveRecord::Base
  belongs_to :project
  belongs_to :person
  belongs_to :role

  has_many :assignments, :dependent => :destroy, :conditions => {:deleted_at => nil}
  accepts_nested_attributes_for :assignments, :allow_destroy => true


  validates_presence_of     :role_id
  validates_presence_of     :project_id
end

我假设控制器将在每个嵌套成员记录的project.save上填充member.project_id。但是,我收到一条验证错误,指出project_id为空。

我的控制器方法:

  def create
    # @project is created in before_filter
    if @project.save
      flash[:notice] = "Successfully created project."
      redirect_to @project
    else
      render :action => 'new'
    end
  end

我是否需要在每个嵌套成员记录中手动设置project_id?或者控制器在创建成员记录时填充的内容是什么?

1 个答案:

答案 0 :(得分:2)

像这样创建Member对象:

@member = @project.members.build