AnApprentice
AnApprentice

Reputation: 111070

Rails - Building a nested model

Project (id)
Permission (project_id, user_id)

When trying to save a project, I get the following error: ActiveRecord::RecordNotSaved (You cannot call create unless the parent is saved):

Controller:

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

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

Suggestions? Thansk

Upvotes: 1

Views: 3527

Answers (2)

edgerunner
edgerunner

Reputation: 14983

Try setting :autosave => true on your association

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

Upvotes: 2

Simon Perepelitsa
Simon Perepelitsa

Reputation: 20649

current_user.projects.new doesn't set user_id for a project, try to use current_user.projects.build instead.

Upvotes: 2

Related Questions