简体   繁体   English

Mongoid:response_with新创建的嵌入式对象引发UrlGenerationError

[英]Mongoid: respond_with newly-created embedded object raises UrlGenerationError

My controller action is supposed to respond_with a newly created User::SmtpConfig record, whose model is embedded inside a User record, but it misidentifies user_id for the new record and raises a UrlGenerationError . 我的控制器动作应该respond_with新创建的User::SmtpConfig记录,它的模型嵌入用户记录里面,但它misidentifies user_id新记录,并提出了一个UrlGenerationError

Error 错误

ActionController::UrlGenerationError at /users/531604866465623cca000000/smtp_configs.json 位于/users/531604866465623cca000000/smtp_configs.json的ActionController :: UrlGenerationError

No route matches {:action=>"show", :controller=>"users/smtp_configs", :user_id=>#<User::SmtpConfig _id: 537a84af6465620a1f090000, uname: "f", pwd: "a", host: "fdsaf", addr: "foo.bar.com", port: nil, tls: nil, auth: nil>, :format=>nil, :id=>nil} missing required keys: [:id] 没有路由匹配{:action =>“ show”,:controller =>“ users / smtp_configs”,:user_id =>#<User :: SmtpConfig _id:537a84af646562020a1f090000,uname:“ f”,pwd:“ a”,主机: “ fdsaf”,addr:“ foo.bar.com”,端口:nil,tls:nil,auth:nil> 、: format => nil,:id => nil}缺少必需的键:[:id]

Controller action 控制器动作

respond_to :json

# This action is reached with the following URL path:
# /users/:user_id/smtp_configs/:id.json
def create
  user = User.find(params[:user_id])
  @smtp = user.smtp_configs.create params
  @smtp.id      # => BSON::ObjectId('537a85286465620a1f0a0000')
  @smtp.user_id # => BSON::ObjectId('531604866465623cca000000')
  respond_with @smtp
end

Why is the controller trying to match any route at all? 为什么控制器要尝试完全匹配任何路由? And why is user_id evaluating to the newly-created object itself? 以及为什么user_id对新创建的对象本身求值?

In the end, my solution was to supply a url as a location option in my respond_with call: 最后,我的解决方案是在我的respond_with调用中提供一个URL作为location选项:

def create
  @user = User.find(params[:user_id])
  @smtp = @user.smtp_configs.create(resource_params)
  respond_with @smtp, location:polymorphic_url(@smtp, {user_id:@user, id:@smtp.id, format: :json})
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM