我正在阅读Rails 3 in Action并按顺序执行命令.但是,当我运行命令时
rails new things_i_bought
cd things_i_bought
bundle install
rails generate scaffold purchase name:string cost:float
Run Code Online (Sandbox Code Playgroud)
这本书说我应该得到这个代码:
class CreatePurchases < ActiveRecord::Migration
def self.up #not created in my code
create_table :purchases do |t|
t.string :name
t.float :cost
t.timestamps
end
end
def self.down # not created in my code
drop_table :purchases
end
end
Run Code Online (Sandbox Code Playgroud)
我得到这个代码:
class CreatePurchases < ActiveRecord::Migration
def change
create_table :purchases do |t|
t.string :name
t.float :cost
t.timestamps
end
end
end
Run Code Online (Sandbox Code Playgroud)
为什么不为我创建上下类方法?我正在使用rails 3.1.1和ruby 1.9.2.
Rya*_*igg 11
谢谢你读我的书!
正如JacobM和dbalatero已经解释过的,这是Rails 3.1中的一个新功能.Aaron Patterson添加了这一特殊功能,作为简化迁移语法的一种方法.在早期版本的Rails中,您必须按照本书所示进行操作:
class CreatePurchases < ActiveRecord::Migration
def self.up
create_table :purchases do |t|
t.string :name
t.float :cost
t.timestamps
end
end
def self.down
drop_table :purchases
end
end
Run Code Online (Sandbox Code Playgroud)
但这有点重复自己.Aaron创建了一个看起来很好且更简单的迁移语法,只调用了向前迁移所需的方法,但也允许向后迁移(称为"回滚").使用Rails 3.1语法编写的相同迁移是:
class CreatePurchases < ActiveRecord::Migration
def change
create_table :purchases do |t|
t.string :name
t.float :cost
t.timestamps
end
end
end
Run Code Online (Sandbox Code Playgroud)
因此,当此迁移"向前"运行时,Rails将使用字段创建购买表.当你向后滚动(或"向后"运行)时,Rails会知道丢弃表格.
然而,这种语法并不完全完美,而且你会遇到像方法这样的问题change_column.当发生这种情况时,最好坚持在迁移中定义def up和def down方法:
class CreatePurchases < ActiveRecord::Migration
def up
change_column :purchases, :cost, :integer
end
def down
change_column :purchases, :cost, :float
end
end
Run Code Online (Sandbox Code Playgroud)
那是因为在这个例子中Rails不知道如何将它切换回以前的类型.我希望这能更好地解释它!
| 归档时间: |
|
| 查看次数: |
1256 次 |
| 最近记录: |