【问题标题】:Ruby on rails - create with wrong data type, it will change to 0 automatically [closed]Ruby on rails - 使用错误的数据类型创建,它将自动更改为 0 [关闭]
【发布时间】:2018-01-24 12:57:57
【问题描述】:

数据库
组名 = varchar
组状态 = int
用户名 varchar
用户状态 = int

普通 POST 案例(完美运行。)
group-name = "组名"
组状态 = 1
用户名“姓名”
用户状态 = 0

特殊 POST 案例(它会将错误的数据类型值更改为 0。)
group-name = "组名"
组状态 = “BBB”
用户名“姓名”
用户状态 = “AAA”

这是因为我想让“AAA”和“BBB”自己使用回滚来处理错误。


Group.transaction do
    group = Group.create(
        name: params["group-name"],
        status: params["group-status"]
    )
    user = User.create(
        name: params["user-name"],
        status: params["user-status"]
    )
end

【问题讨论】:

  • 为字段添加验证,Rails 不会插入

标签: mysql ruby-on-rails ruby


【解决方案1】:

如果我没看错,您只需要验证相关模型中的数值即可。阅读文档以获取更多信息here

所以添加:

class Group < ApplicationRecord
  ...
  validates :status, numericality: { only_integer: true, allow_nil: true }
  ...
end

class User < ApplicationRecord
  ...
  validates :status, numericality: { only_integer: true, allow_nil: true }
  ...
end

如果数据类型不正确,这将提供错误,您可以按照前面的讨论进行处理。

希望对您有所帮助 - 如果您有任何问题,请告诉我!

【讨论】:

  • @kase - 这对你有用吗?
猜你喜欢
  • 2014-02-16
  • 2011-09-06
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 2015-06-02
  • 2016-01-24
相关资源
最近更新 更多