Rails validation enable error 'not included in list'

Hello everyone. I saw several problems similar to mine, but none of the solutions seemed to solve my problem, so after a day and a half, trying to fix everything that I decided to try, deleted my problem.

I have a table that in MySQL db with this model:

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 

So, I want client_status and client_type to be only numeric values ​​between 0 and 2, here is the rspec I wrote to put this:

 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 

This is a pretty simple test, I have true for client_status and client_type, so I have to add them to RSPEC, however running this rspec gives me this error message:

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

I tried this to see what the output is:

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

I got this conclusion:

 client type is: false and status is: . 

Thank you for reading this long post, and I really hope that someone can shed light on this question for me.

Note. I changed the names of the / rspec model and some fields so that I did not violate my NDA companies.

Regards, Surep

+5
source share
2 answers
  • In rails, you need to separate the validators by a comma:
  validates: client_status, presence: true, inclusion: {in: 0..2} 
  1. It makes no sense to check for availability if you check for inclusion. This way you can simplify the code by simply checking:
  validates: client_status, inclusion: {in: 0..2} 
+5
source

I think you should use numericality: as follows:

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

Source: https://habr.com/ru/post/1204283/


All Articles