Ruby 在 Rails 上将列更改为 Null,不起作用?
Ruby On Rails Change Column to Null, Not Work?
我在终端中命令将数据库中的列更改为非空,但似乎不起作用。
rails g migration change_column_null :Speaker, :surname, false
我有一个文件 ChangeColumnNull 但是里面什么都没有。
class ChangeColumnNull < ActiveRecord::Migration
def change
end
end
讲座控制器(默认创建):
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
表格
<%= 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>
删除该迁移并使用更好的名称编写一个空白迁移,然后通过设置默认值来填充它。如果您有默认值,它将永远不会为空。
rails g migration ChangeColumnOnTableName
然后在该迁移中执行以下操作:
change_column :name_of_table, :name_of_column, :data_type_of_column, :null => false
如果您只是担心它根据用户输入的内容为空,您可以简单地添加一个需要它的验证。在您的模型中:
validates :name_of_column, presence: true
如果您使用的是最新的 ruby (2.5+) 这是将字段从 NOT NULL 更改为 NULL
的迁移脚本
class ChangeEmailPasswordToNullableUsers < ActiveRecord::Migration[5.2]
def change
change_column_null :users, :email, true
change_column_null :users, :password, true
end
end
我在终端中命令将数据库中的列更改为非空,但似乎不起作用。
rails g migration change_column_null :Speaker, :surname, false
我有一个文件 ChangeColumnNull 但是里面什么都没有。
class ChangeColumnNull < ActiveRecord::Migration
def change
end
end
讲座控制器(默认创建):
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
表格
<%= 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>
删除该迁移并使用更好的名称编写一个空白迁移,然后通过设置默认值来填充它。如果您有默认值,它将永远不会为空。
rails g migration ChangeColumnOnTableName
然后在该迁移中执行以下操作:
change_column :name_of_table, :name_of_column, :data_type_of_column, :null => false
如果您只是担心它根据用户输入的内容为空,您可以简单地添加一个需要它的验证。在您的模型中:
validates :name_of_column, presence: true
如果您使用的是最新的 ruby (2.5+) 这是将字段从 NOT NULL 更改为 NULL
的迁移脚本
class ChangeEmailPasswordToNullableUsers < ActiveRecord::Migration[5.2]
def change
change_column_null :users, :email, true
change_column_null :users, :password, true
end
end