2011-05-20 155 views
4

嘿,大家好,感谢提前检查我的问题。JSON,respond_with和嵌套资源路由错误?

我有嵌套的路线,像这样:

resources :users do 
    resources :avatars 
end 

而且在创建一个用户,我也创建了一个化身,像这样:

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 

然而,在做出服务器请求会创建一个不适当的用户对象(应导致JSON响应{error_key => ...}),rails会给我以下错误:

ActionController::RoutingError (No route matches {:user_id=>#<User id: nil, name: nil, phone_number: "mcdkls", email: "[email protected]", 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' 

好像Rails正在试图显示HTML,而不是JSON,但如果我改变我的控制器,就像这样:

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的我返回一个美丽的名字{=>“不能为空”}。有什么想法吗?

万分感谢, 贾里德

+0

可以告诉你的代码片段或服务器的输出,显示什么被回复的实际网址是? – jaydel 2011-05-20 11:58:05

+0

这里有同样的问题。你知道如何解决它吗? – 2011-09-27 21:35:45

+0

重复http://stackoverflow.com/questions/6770439/rails-nested-resource-with-respond-with-destroy-action – 2011-09-27 21:39:25

回答

0

没有实际测试这一点,但也许问题是在调用“respond_with”多个对象?取而代之的,则尝试将对象转换成数组:

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 

见respond_with代码贡献者,何塞·Valim的最后的评论在这里:

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