Joe Joe - 7 months ago 28
Ruby Question

Ruby on rials Change Column to Null, Not Work?

I command in Terminal to change on column in database to not null, but It seems not work.

rails g migration change_column_null :Speaker, :surname, false


I got a file ChangeColumnNull But inside, it is nothing.

class ChangeColumnNull < ActiveRecord::Migration
def change
end
end


I do not know why it is no working...
Thanks Guys

Answer

Erase that migration and write a blank migration with a better name and then fill it out by setting a default value. If you have a default value it will never be null.

rails g migration ChangeColumnOnTableName

Then inside that migration do the following:

change_column :name_of_table, :name_of_column, :data_type_of_column, :null => false

If you're only worried about it being null based on what a user enters, you could simply add a validation that requires it. In your model:

validates_presence_of :name_of_column