【问题标题】:Mongoid: respond_with newly-created embedded object raises UrlGenerationErrorMongoid:respond_with 新创建的嵌入对象引发 UrlGenerationError
【发布时间】:2014-05-29 23:17:15
【问题描述】:

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

错误

/users/531604866465623cca000000/smtp_configs.json 处的 ActionController::UrlGenerationError

没有路由匹配 {:action=>"show", :controller=>"users/smtp_configs", :user_id=>#<:smtpconfig _id: uname: nil auth:>, :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 会评估新创建的对象本身?

【问题讨论】:

  • 这个问题(创建后尝试查找显示方法)通常在方法创建无法正常工作时出现。在你的情况下,它似乎工作正常。试试render json: @smtp。你也使用params,但在rails 4中它不应该因为强大的参数而工作(不确定)
  • render json: @smtp 确实有效,但不太理想,因为它不包含验证错误。

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


【解决方案1】:

最后,我的解决方案是在我的respond_with 调用中提供一个网址作为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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多