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

时间:2014-05-19 22:42:10

标签: ruby-on-rails ruby-on-rails-4 mongoid

我的控制器操作应该是respond_with新创建的User::SmtpConfig记录,其模型嵌入在用户记录中,但它错误地标识user_id新记录并引发UrlGenerationError 1}}。

错误

  

Actionusetroller :: UrlGenerationError at /users/531604866465623cca000000/smtp_configs.json

     

没有路由匹配{:action =>“show”,:controller =>“users / smtp_configs”,   :user_id =>#< User :: SmtpConfig _id:537a84af6465620a1f090000,uname:   “f”,pwd:“a”,主持人:“fdsaf”,地址:“foo.bar.com”,port:nil,tls:   nil,auth:nil>,:format => nil,:id => nil}缺少必需的键:[:id]

控制器操作

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

为什么控制器会尝试匹配任何路线?为什么user_id会评估新创建的对象本身?

1 个答案:

答案 0 :(得分:1)

最后,我的解决方案是在location电话中提供respond_with选项的网址:

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