1

My migration file contains:

t.belongs_to :user,      index: true
t.belongs_to :organization, index: true
t.boolean :member,       default: false, null: false
t.boolean :admin,        default: false, null: false
t.boolean :moderator,    default: false, null: false

The model file includes:

validates :member, presence: true
validates :admin, presence: true
validates :moderator, presence: true

In my seeds file I create a new record:

user.relationships.create!(organization_id: 2, member: true, moderator: true)

This fails with the error Admin can't be blank and indeed if I add admin: false to the seeds line, the error is gone. But I would expect that when I don't specify the value for admin, it would take on its default value from the migration file. Why is its behaviour different from my expectation? Am I doing something wrong or is my expectation incorrect so that I always need to specify values for variables that are not allowed to be nil?

Marty
  • 2,132
  • 4
  • 21
  • 47
  • you donot need to add validation when you are already doing default: false at db level. – Athar Aug 01 '15 at 19:25
  • 1
    this is the same issue you as reported http://stackoverflow.com/questions/10506575/rails-database-defaults-and-model-validation-for-boolean-fields. try to add this `validates :admin, :inclusion => {:in => [true, false]}` rather than presence. – Athar Aug 01 '15 at 19:33
  • 1
    Thanks @Athar. That indeed worked! – Marty Aug 01 '15 at 20:38

1 Answers1

1

The validates instruction checks if the attribute is present at creation time (and it isn't as you don't specify it in the parameters of create).

Removing validates :admin, presence: true leads to applying the default value (false) when admin is not specified.

Felipe Arenales
  • 991
  • 1
  • 8
  • 19