JSON, response_with, and nested resource routing error?

Hi everyone, Thanks in advance for checking out my question.

I have nested routes:

resources :users do resources :avatars end 

And when creating the user, I also create an avatar:

 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, after requesting a server that will create an inadequate User object (which should lead to a JSON response {error_key => ...}), the rails give 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' 

It looks like Rails is trying to render HTML, not JSON, but if I change my controller like this:

 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 a beautiful {name => "cannot be empty"} for me. Any thoughts?

Thanks a million, Jared

+4
source share
1 answer

This is not actually verified, but perhaps the problem is that multiple objects in your reply_with call? Instead, try placing objects in 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 response_with code contributor, Jose Valima, last comment here:

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

0
source

All Articles