使用RoR 脚本Generator产生controller test
脚本如下:
>script/generate controller test
产生如下文件:
exists app/controllers/
exists app/helpers/
create app/views/test
exists test/functional/
exists test/unit/helpers/
create app/controllers/test_controller.rb
create test/functional/test_controller_test.rb
create app/helpers/test_helper.rb
identical test/unit/helpers/test_helper_test.rb
要想建立数据库model,并产生表,可以使用如下脚本命令:
如:建立数据库表notices(对应着类:Notice,这其中涉及到rails的名字自动转变)
>script/generate model notice
产生如下文件:
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/notice.rb
create test/unit/notice_test.rb
create test/fixtures/notices.yml
exists db/migrate
create db/migrate/20091010031714_create_notices.rb
其中:
create app/models/notice.rb显示产生notice.rb文件,类名是Notice,文件内容如下:
class Notice < ActiveRecord::Base
end
create db/migrate/20091010031714_create_notices.rb显示在db目录的子目录migrate产生20091010031714_create_notices.rb文件,名字前的20091010031714事rails用来防止文件冲突的一种时间戳,文件内容如下:
class CreateNotices < ActiveRecord::Migration
def self.up
create_table :notices do |t|
t.timestamps
end
end
def self.down
drop_table :notices
end
end
要想在表notices中建立不同的列,修改如下
class CreateNotices < ActiveRecord::Migration
def self.up(用来生成表)
create_table :notices do |t|
t.string :title(建立string类型的title列)
t.string :content
t.integer :order_index(建立integer类型的order_index列)
t.integer :is_show
t.timestamps(此列是rails自动生成的,会自动生成datetime类型的created_time和updated_time列,不需要时可以去掉)
end
end
def self.down(用来删除表)
drop_table :notices
end
end
当修改后,为了在数据库真正建立表notices,可以使用如下命令
>rake db:migrate
输出:
== CreateNotices: migrating ==================================================
-- create_table(:notices)
-> 0.0310s
== CreateNotices: migrated (0.0310s) =========================================
产生表notices
在生成表后,如果修改表notices中的列字段,可以使用脚本如下
>script/generate migration change_is_show_to_notice
change_is_show_to_notice名字表示修改notice表中的is_show字段
运行输出如下:
exists db/migrate
create db/migrate/20091010034904_change_is_show_to_notice.rb
20091010034904_change_is_show_to_notice.rb文件内容如下:
class ChangeIsShowToNotice < ActiveRecord::Migration
def self.up
end
def self.down
end
end
修改:
class ChangeIsShowToNotice < ActiveRecord::Migration
def self.up
change_column(:notices, :is_show, :boolean)(改变is_show类型为boolean型)
change_column_default(:notices, :is_show, 0)(改变is_show 的默认值为0)
change_column_default(:notices, :order_index, -1)
end
def self.down
end
end
把修改持久化到表,运行如下命令;
>rake db:migrate
(in D:/rwork/ShellSNS)
== ChangeIsShowToNotice: migrating ===========================================
-- change_column(:notices, :is_show, :boolean)
-> 0.1400s
-- change_column_default(:notices, :is_show, 0)
-> 0.0160s
-- change_column_default(:notices, :order_index, -1)
-> 0.0160s
== ChangeIsShowToNotice: migrated (0.1720s) ==================================