gpt4 book ai didi

ruby-on-rails - JSON、response_with 和嵌套资源路由错误?

转载 作者:行者123 更新时间:2023-12-04 05:53:34 26 4
gpt4 key购买 nike

大家好, 提前感谢您检查我的问题。

我有这样的嵌套路由:

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

但是,在发出会创建不合适的 User 对象的服务器请求(应该导致 JSON 响应 {error_key => ...})时,rails 给我以下错误:
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'

似乎 Rails 试图显示 HTML 而不是 JSON,但是如果我像这样更改 Controller :
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 为我返回了一个漂亮的 {name => "can't be blank"}。有什么想法吗?

太感谢了,
贾里德

最佳答案

尚未对此进行实际测试,但问题可能出在您对“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

请参阅 response_with 代码的贡献者,Jose Valim 在此处的最后评论:

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

关于ruby-on-rails - JSON、response_with 和嵌套资源路由错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6066784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com