ruby Rails验证包含错误'not included in list'

sxissh06  于 2023-10-17  发布在  Ruby
关注(0)|答案(2)|浏览(128)

我有一个表,在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设置了presence true,所以我必须在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的名称和一些字段,以便不违反公司的保密协议。

56lgkhnf

56lgkhnf1#

1.在rails中,你需要用逗号分隔验证器:

validates :client_status, presence: true, inclusion: { in: 0..2 }

1.如果你检查包容性,检查存在就没有意义了。所以你可以通过简单的验证来简化你的代码:

validates :client_status, inclusion: { in: 0..2 }
kcwpcxri

kcwpcxri2#

numericality:应该这样使用:

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

相关问题