4

Hey Everybody, Thanks in advance for checking out my question.

I've got nested routes like so:

resources :users do
  resources :avatars
end

And upon creating a user, I also create an avatar like so:

def create
  @user = User.create(params[:user])
  @avatar = Avatar.create(:user_id => @user)
  # Send both User and Avatar object back
  respond_with(@user,@avatar)
end

HOWEVER, upon making a server request that would create an inadequate User object (that should result in JSON response {error_key => ...}), rails gives me the following error:

ActionController::RoutingError (No route matches {:user_id=>#<User id: nil, name: nil, phone_number: "mcdkls", email: "fdsa@cmadksl", password_hash: nil, password_salt: nil, auth_token: nil, admin: false>, :action=>"show", :controller=>"avatars", :id=>#<Avatar id: 19, user_id: 1, created_at: "2011-05-20 01:52:22", updated_at: "2011-05-20 01:52:22">}):
app/controllers/users_controller.rb:13:in `create'

Seems like Rails is attempting to display HTML rather than JSON, but if I alter my controller like so:

def create
  @user = User.create(params[:user])
  @avatar = Avatar.create(:user_id => @user)
  # Send both User and Avatar object back
  respond_with(@user)
end

Rails returns for me a beautiful {name => "can't be blank"}. Any thoughts?

Thanks a million, Jared

Jared Goodner
  • 161
  • 2
  • 11

1 Answers1

0

Haven't actually tested this, but maybe the issue is the multiple objects in your call to 'respond_with'? Instead, try putting the objects into an array:

def create
  @user = User.create(params[:user])
  @avatar = Avatar.create(:user_id => @user)
  # Send both User and Avatar object back
  respond_with([@user,@avatar])
end

See the contributor of the respond_with code, Jose Valim's last comment here:

http://archives.ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with

Ryan Dugan
  • 563
  • 1
  • 5
  • 8