Search code examples
sqlruby-on-railsmigrationdatabase-migration

Beginner Rails Migration & Column Options in ActiveRecord


Quick question on :null option in ActiveRecord table creation.

Let's say I was to create a new table with a column description.

def change
    create_table :products do |t|
        t.string :name
        t.text :description, null: false
    end
end

If I don't have any :presence validation in my model regarding the description column, then shouldn't "nothing" be able to be passed into the description column? I'm not sure what null: false can do to stop me from passing nothing in since I don't have any validation in place.


Solution

  • Rails migration or schema options like null: false operate on database level (storage). If you tried to save record with empty description field, you would receive a database error (e.g. generated by PostgreSQL) wrapped in a ActiveRecord::StatementInvalid:. On calling object.valid? the object would have been valid from the application point of view (Rails).

    Rails validations like :presence operate on application level. In this case passing a null value would create an object which would return false on valid? and you could easily access error messages from the object by calling object.errors. If not bypassing validations, Rails would not allow you to save such a record to the database.