Joe
Joe

Reputation: 107

Ruby On Rails 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

Lecture Controller (Def Create):

class CplecturesController < ApplicationController
layout 'cp_layout'

 def create
@lecture = Lecture.new(lecture_params)

@lecture.save
redirect_to @lecture
end

private
def lecture_params
  params.require(:lecture).permit(:lecture_title, :lecture_day,   :column, :start_time, :end_time, :registered_speakers, :guest_speakers, :description)
end
end

Forms

 <%= form_for :lecture, url:lectures_path do |f| %>
 <form>
 <div class="form-group">
  <%=label_tag "Lecture Title" %><br>
  <%= f.text_field :lecture_title, :class => "form-control",   :placeholder => "Example: Why is Wordpress the best?" %>
</div>

Upvotes: 0

Views: 5588

Answers (2)

Manjunath Reddy
Manjunath Reddy

Reputation: 1197

if you are using latest ruby (2.5+) Here is the migration script to change fields from NOT NULL to NULL

class ChangeEmailPasswordToNullableUsers < ActiveRecord::Migration[5.2] def change change_column_null :users, :email, true change_column_null :users, :password, true end end

Upvotes: 1

toddmetheny
toddmetheny

Reputation: 4443

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 :name_of_column, presence: true

Upvotes: 6

Related Questions