Rails - 构建嵌套模型

时间:2011-02-16 08:08:16

标签: ruby-on-rails ruby-on-rails-3

Project (id)
Permission (project_id, user_id)

尝试保存项目时,出现以下错误:ActiveRecord :: RecordNotSaved(除非保存父项,否则无法调用create):

控制器:

@project = current_user.projects.new(:name => params[:project][:name])
@project.permissions.build(:user_id => current_user.id)

respond_to do |format|
  if @project.save
  ......

连连呢? Thansk

2 个答案:

答案 0 :(得分:2)

current_user.projects.new没有为项目设置user_id,请尝试使用current_user.projects.build

答案 1 :(得分:2)

尝试在关联中设置:autosave => true

class Project < ActiveRecord::Base
  has_many :permissions, :autosave => true
  …