如何将方法添加到Rails ActiveRecord类中?

2026-04-11 19:132阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计374个文字,预计阅读时间需要2分钟。

如何将方法添加到Rails ActiveRecord类中?

在纯Ruby中,这样可以很好使用:

rubyclass TestSuper def foo puts In TestSuper.foo endend

class TestClass

def bar puts In TestClass.bar, second definition puts Calling foo: endend

在纯 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中发生这种情况,我该如何解决呢?

如何将方法添加到Rails ActiveRecord类中?

理论#2:在迁移的顶部

require 'app/models/my_model'

本文共计374个文字,预计阅读时间需要2分钟。

如何将方法添加到Rails ActiveRecord类中?

在纯Ruby中,这样可以很好使用:

rubyclass TestSuper def foo puts In TestSuper.foo endend

class TestClass

def bar puts In TestClass.bar, second definition puts Calling foo: endend

在纯 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中发生这种情况,我该如何解决呢?

如何将方法添加到Rails ActiveRecord类中?

理论#2:在迁移的顶部

require 'app/models/my_model'