【问题标题】:Rails validation inclusion error 'not included in list'Rails 验证包含错误“未包含在列表中”
【发布时间】:2014-10-08 20:06:31
【问题描述】:

大家好,我遇到了几个与我类似的问题,但似乎没有一个解决方案能解决我的问题,所以在尝试了一天半之后,我决定试试运气来发布我的问题。

我有一个在 MySQL 数据库中使用此模型的表:

class Client< ActiveRecord::Base

  validates :name, :length => {:maximum => 255}, :presence => true
  validates :client_status, inclusion: { in: 0..2, :presence => true }
  validates :client_type, inclusion: { in: 0..2, :presence => true}
end

所以我希望 client_status 和 client_type 只能是 0 到 2 之间的数值,这是我写的 rspec 来适应这个:

describe Client do
  before do
    @client = Client.new
  end

  it "should allow name that is less than 255 characters" do
    long_char = 'a' *254
    @client.name = long_char
    @client.client_status = 0
    @client.client_type = 1
    @client.should be_valid
  end

end

这是一个非常简单的测试,我的 client_status 和 client_type 都存在,所以我必须在 RSPEC 中添加它们,但是运行这个 rspec 会给我这个错误消息:

got errors: Value type is not included in the list, Status is not included in the list

我试过这个,看看输出是什么:

puts "client type is: #{@client.client_type} and status is: #{@client.client_status} ."

我收到了这个输出:

client type is: false and status is:  .

感谢您阅读这篇长文,我真的希望有人能为我阐明这个问题。

注意:我已更改模型/rspec 的名称和一些字段,以免违反我公司的 NDA。

问候, 没错

【问题讨论】:

  • 这个表的架构是什么样子的?特别是client_type和client_status的类型是什么?它们真的是整数吗?
  • 尝试将inclusion: { in: 0..2, :presence =&gt; true } 更改为inclusion: { in: 0..2}, :presence =&gt; true
  • 我在一个空白项目上尝试了您的代码,但我无法重现您报告的内容。您发布的代码至少可以在 Ruby 2.0、Rails 4.1、RSpec 3.1 中正常运行。
  • 听起来属性是在您的代码中自动设置的。在您的客户端模型中搜索 client_statusclient_type 并注意 before_validation 挂钩。看看潜在的二传手,甚至可能assign_attributes 被覆盖了。
  • 你的puts“调试语句”在@client.should be_valid行之前和之后分别输出什么?

标签: ruby-on-rails ruby validation rspec inclusion


【解决方案1】:
  1. 在 Rails 中,您需要用逗号分隔验证器:
 验证:client_status,存在:true,包含:{ in: 0..2 }
  1. 如果检查包含,检查存在是没有意义的。因此,您可以通过简单的验证来简化您的代码:
 验证:client_status,包含:{ in: 0..2 }

【讨论】:

  • db中有client_status和client_type整数列吗?
  • 是的,它们都是数据库中的 TINYINT
  • 将其标记为正确答案,因为这是应该如何完成的,我的解决方案是我在数据库中设置的数据类型存在问题,不应该是 tinyint,而是整数。
  • 你应该写下那个答案然后接受它。
【解决方案2】:

我认为你应该像这样使用numericality:

validates :client_status, numericality: { only_integer: true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 2 }, :presence => true

【讨论】:

  • 我试过这个并且得到错误'得到错误:客户端类型不能为空,客户端状态不能为空'要添加到此,puts语句仍然分别显示false和'' .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
相关资源
最近更新 更多