1

The variable var is a boolean and should not be allowed to be blank. Therefore in my model file I have:

validates_inclusion_of :var, :in => [true, false]
validates :var, presence: true

In my seeds file I have:

title = "abc"
var = [true, false].sample
author.articles.create!( title: title,
                         var: var)

Seeding produces the error:

ActiveRecord::RecordInvalid: Validation failed: Var can't be blank

Does anyone understand why it wants to create an article with a blank var?

Update: Using the debugger, I can confirm that var had a value of 1.

Schema for articles:

  create_table "articles", force: :cascade do |t|
    t.integer  "author_id"
    t.string   "title",          limit: 50,                null: false
    t.boolean  "var",                       default: true, null: false
    t.datetime "created_at",                               null: false
    t.datetime "updated_at",                               null: false
  end
Marty
  • 2,132
  • 4
  • 21
  • 47
  • I also tried `var = [0, 1].sample` but that made no difference. I use `.sample` at other locations of seeds as well, without problems. – Marty Dec 29 '15 at 13:09

1 Answers1

1

should not be allowed to be blank

A better way will be to set a default value in the db.

Not only will this free up Rails processing power, but will also make sure that no matter what, that value has to be present, a necessity for boolean:

$ rails g migration AddDefaultToBool

# db/migrate/add_default_to_bool____________.rb
class AddDefaultToBool < ActiveRecord::Migration
   def change
      change_column :articles, :var, :boolean, default: false
   end
end

$ rake db:migrate

This way, you'll always have the boolean as false if the value is not present. I know it's not specifically what you're asking, but will be a better solution anyway.


In terms of your validation, you'll want to use the newer validates shorthand:

#app/models/article.rb
class Article < ActiveRecord::Base
   validates :var, presence: true, inclusion: [:true, :false]
end

According to comments on this question, you shouldn't have presence for a boolean value:

Note that you cannot have the usual validation for the presence (validates :field, presence: true) for a boolean field (the field would not be valid for a false value).

But in both Rails 3 and 4, having validates :field, inclusion: [true, false] would test for inclusion in a list of values, with the side-effect to test for the field's presence (unless one of those values is nil of course). – Martin Carel Jul 14 at 19:38

... so you should be able to use the following:

#app/models/article.rb
class Article < ActiveRecord::Base
   validates :var, inclusion: [:true, :false]
end

Another good ref

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147