Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validation inclusion error 'not included in list'

Hi all I have seen several issues similar to mine but none of the solutions seem to solve my issue so after a day and a half of trying everything I've decided to try my luck posting my problem.

I have a table which in a 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 the client_status and the client_type to only be numeric values between 0 and 2, here is the rspec I wrote to accommodate 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 presence true for both client_status and client_type so I must add those in the 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 received this output:

client type is: false and status is:  .

Thank you for reading this long post and I really hope someone can shed some light on this issue for me.

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

Regards, Surep

like image 761
Surep Avatar asked Oct 08 '14 20:10

Surep


2 Answers

  1. In rails you need to divide validators by comma:
    validates :client_status, presence: true, inclusion: { in: 0..2 }
  1. It has no sense to check presence, if you check on inclusion. So you can simplify your code by simple validation:
    validates :client_status, inclusion: { in: 0..2 }
like image 159
Alexander Karmes Avatar answered Oct 22 '22 06:10

Alexander Karmes


I think you should use numericality: like this:

validates :client_status, numericality: { only_integer: true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 2 }, :presence => true
like image 35
Fred Perrin Avatar answered Oct 22 '22 07:10

Fred Perrin