Rails验证包含错误'未包含在列表中'

时间:2014-10-08 20:06:32

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

大家好我已经看过几个与我类似的问题,但没有一个解决方案似乎解决了我的问题所以经过一天半的尝试,我决定尝试运气发布我的问题。

我在这个模型的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:  .

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

注意:我更改了model / rspec和某些字段的名称,这样我就不会违反我公司的NDA。

此致 Surep

2 个答案:

答案 0 :(得分:6)

  1. 在rails中,您需要用逗号分隔验证器:
  2.     validates :client_status, presence: true, inclusion: { in: 0..2 }
    1. 如果检查包含,检查在线状态是没有意义的。因此,您可以通过简单的验证来简化代码:
    2.     validates :client_status, inclusion: { in: 0..2 }

答案 1 :(得分:1)

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

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