这种行为非常酷,因为它可以很容易地编写“futureproof”迁移,其中迁移定义模型类内联,以防稍后从类代码库中删除该类。但它是如何运作的?
$ rails c
pry(main)> User.methods.count
=> 686
pry(main)> class User < ActiveRecord::Base; end
=> nil
pry(main)> User.methods.count
=> 686
以下是迁移:
class FrobulateUsers < ActiveRecord::Migration
puts User.methods.count
class User < ActiveRecord::Base
end
puts User.methods.count
...
end
当我运行它时:
$ rake db:migrate
687
666
为什么方法会在迁移中消失,但不会在控制台中消失?
答案 0 :(得分:2)
弄乱这个,这是真正的类名......
class FrobulateUsers < ActiveRecord::Migration
puts User.name
class User < ActiveRecord::Base
end
puts User.name
end
User
FrobulateUsers::User
注意,你可以把它放在课堂外面......
# 20150810221740_frobulate_users.rb
class User < ActiveRecord::Base
end
class FrobulateUsers < ActiveRecord::Migration
puts User.name
end
User