【问题标题】:Updating an integer field of a Rails model with string strong parameters使用字符串强参数更新 Rails 模型的整数字段
【发布时间】:2020-05-26 09:54:11
【问题描述】:

在我的控制器中,我想在我的更新方法中将字段更新为我的模型对象。我的模型的一些字段是整数类型。但是,这些字段是 params 对象中的字符串。

我想做

  def profile_params
    params
      .require(:client)
      .permit(:marital_status, :name, ...)
  end

  def update
    @client = Client.find params[:id]
    @client = Client.update(profile_params)
  end

但我收到以下错误

ArgumentError - '0' 不是有效的 marital_status。

果然,如果在我的profile_params.rb 中我将marital_status 转换为整数,该特定错误就会消失,但我的Client 类中有很多字段是整数。我想有一个比手动转换每个字段更好的解决方案。或者即使我必须这样做,组织代码的最佳方式是什么?

编辑:这是客户端模型的摘要


class Client < ApplicationRecord

  enum marital_status: %i[single married divorced separated widowed]

end

传递给控制器​​的参数如下所示:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"tLUZ0bb6tRRkx/OFNVbhCT/AnrudPbCQMvOakw9HyiHkiqMip5tkDnYsF2F/e7TE4VkmIgF1hxtYI78Pw2bsSw==", "client"=>{"id"=>"517", "marital_status"=>"0"}, "id"=>"517"}

【问题讨论】:

  • 显示您的 profile_params.rb、您的数据库迁移和您的输入表单
  • 听起来(可能还有其他)是枚举,对吗?
  • 同意@RockwellRice,marital_statusenum,尽管他没有展示他的模型。 param 中的 marital_statusnil,因此它将 nil 转换为 0,而 enum 中不存在该 enum
  • 感谢您的所有意见;我已经更新了我的问题。来自表单的输入实际上是一个“0”字符串。
  • 向我们展示表单元素以选择状态?

标签: ruby-on-rails controller strong-parameters


【解决方案1】:

我认为在从profile_params 读取值时,除了使用.to_i 之外别无他法。

枚举很棘手,因为您可以通过键或值来使用它们。

假设你的枚举:

Client.marital_statuses
#  => {"single"=>0, "married"=>1, "divorced"=>2, "separated"=>3, "widowed"=>4}

使用值(索引)赋值:

c1 = Client.new
c1.marital_status = 0
c1.marital_status
#  => "single"
c1.marital_status_before_type_cast
#  => 0

使用键(名称)分配:

c2 = Client.new
c2.marital_status = 'married'
c2.marital_status
#  => "married"
c2.marital_status_before_type_cast
#  => "married"

我认为这就是 Rails 不将 String 转换为 Integer 的原因,因为它不知道应该使用值(索引)而不是键(名称)。

c3 = Client.new
c3.marital_status = '0'
# Traceback (most recent call last):
#         2: from (irb):6
#         1: from (irb):7:in `rescue in irb_binding'
# ArgumentError ('0' is not a valid marital_status)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2014-10-24
    • 1970-01-01
    • 2017-09-14
    • 2022-10-17
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多