加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails验证包含错误’未包含在列表中’

发布时间:2020-12-17 03:32:23 所属栏目:百科 来源:网络整理
导读:大家好我已经看到了几个类似于我的问题,但没有一个解决方案似乎解决了我的问题所以经过一天半的尝试,我决定尝试运气发布我的问题. 我在这个模型的MySQL数据库中有一个表: class Client ActiveRecord::Base validates :name,:length = {:maximum = 255},:pre
大家好我已经看到了几个类似于我的问题,但没有一个解决方案似乎解决了我的问题所以经过一天半的尝试,我决定尝试运气发布我的问题.

我在这个模型的MySQL数据库中有一个表:

class Client< ActiveRecord::Base

  validates :name,:length => {:maximum => 255},:presence => true
  validates :client_status,inclusion: { in: 0..2,:presence => true }
  validates :client_type,: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

解决方法

>在rails中,您需要用逗号分隔验证器:

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

>如果检查包含,检查存在是没有意义的.因此,您可以通过简单的验证来简化代码:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读