Help with nested creation: what am I doing wrong?

I’ve got nested scaffolded resource objects as indicated below. All
the routing and display stuff seems to work properly, but when I
create a new identity, it shows up in the database with a NULL
user_id, even though I’m creating the object via the identities
attribute of a user object. What am I missing?

Relevant snippets:

config/routes.rb:
map.resources :users do |users|
users.resources :identities
end

models/user.rb:
class User < ActiveRecord::Base
has_many :identities
end

models/identity.rb:
class Identity < ActiveRecord::Base
belongs_to :user
end

controllers/identities_controller.rb:
class IdentitiesController < ApplicationController
before_filter :get_user

def get_user
@user = User.find(params[:user_id])
end

def create
@identity = @user.identities.new(params[:identity])
respond_to do |format|
if @identity.save
flash[:notice] = ‘Identity was successfully created.’
format.html { redirect_to identity_url(@user, @identity) }
format.xml { head :created, :location =>
identity_url(@user,
@identity) }
else
format.html { render :action => “new” }
format.xml { render :xml => @identity.errors.to_xml }
end
end
end

end

try changing
@identity = @user.identities.new(params[:identity])

to
@identity = @user.identities.build(params[:identity])

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs