当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – 将方法添加到Rails ActiveRecord类

来源:互联网 收集:自由互联 发布时间:2021-06-23
在纯 Ruby中,这很好用: class TestSuper def foo puts "In TestSuper.foo" endendclass TestClass TestSuper def foo super puts "In TestClass.bar" endendclass TestClass def bar puts "In TestClass.bar, second definition" puts "Calling foo:
在纯 Ruby中,这很好用:

class TestSuper
  def foo
    puts "In TestSuper.foo"
  end
end

class TestClass < TestSuper
  def foo
    super
    puts "In TestClass.bar"
  end
end

class TestClass
  def bar
    puts "In TestClass.bar, second definition"
    puts "Calling foo:"
    foo
  end
end

t = TestClass.new
t.foo
t.bar

我可以在TestClass实例上调用foo()和bar()并获得我期望的结果:

In TestSuper.foo
In TestClass.bar
In TestClass.bar, second definition
Calling foo:
In TestSuper.foo
In TestClass.bar

但是,当我在Rails迁移中尝试非常类似的东西时,我会收到错误:

#### my_model.rb ####
puts "In my_model.rb"
class MyModel
  has_many :foo
end

#### my_migration.rb ####
puts "In my_migration.rb"
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

class MyMigration < ActiveRecord::Migration
  def self.up
    MyModel.find(1).bar        
  end

  def self.down
    # Not applicable
  end
end

第一个问题是除非我明确地在my_migration.rb中扩展ActiveRecord,否则MyModel.find()会消失.否则,它会丢弃超类.

如果我这样做,那么我在MyModel.bar()中的foo调用上得到一个错误.

如果我在my_migration.rb中注释掉类(重新)定义,find()和bar()都可以正常工作.

在调试过程中,我添加了puts语句,以查看每个文件和时间.上课正在执行中.如果MyModel已经定义(我正在my_migration.rb中进行),似乎my_model.rb甚至都没有加载.

那么:为什么会在Rails中发生这种情况,我该如何解决呢?

理论#2:在迁移的顶部

require 'app/models/my_model'
网友评论