繁体   English   中英

ActionController::Parameters 将整数转换为字符串

[英]ActionController::Parameters converts integer to string

我在 rails 5 中定义user_params ,如下所示:

def training_plan_params
  params.require(:training_plan).permit(
    :training_plan_id, 
    :sport_id, 
    :distance,
    lastTrainingStatus: [:duration,:reps,:type,:level],
    trainings: [:text, :order, :level],
    modified: [:level,:duration]
  )
end

但是当我将参数发送到 Rails 时,如下所示:

{ training_plan: { sport_id: 2, distance: 900 } }

它不会将控制器中的距离检索为整数,如下所示:

=> <ActionController::Parameters {"sport_id"=>"2", "distance"=>"900"} permitted: true>

=> training_plan_params[:distance]
=> "900"

有没有办法保持其类型而不是将其转换为字符串?

今天也在处理同样的问题,我做了一些搜索。 我发现这篇文章: Rails 测试正在将我的整数数组转换为字符串数组

基本上,问题在于您(我们)使用 ActionDispatch::IntegrationTest 的方式,而不是 ActionController::Parameters。 我通过使用.to_json将输入转换为我的 PUT/POST 调用并将headers: { 'Content-Type': 'application/json' }提供给 PUT/POST 调用来解决这个问题。 然后导致测试路由器将我的数据视为 json 并保留类型,而不是默认将事物视为文本。

暂无
暂无

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

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