相关疑难解决方法(0)

Rails在迁移之间共享代码(也称为关注点)

我在相同的助手中进行了一些迁移

  private

  def add_earthdistance_index table_name, options = {}
    execute "CREATE INDEX %s_earthdistance_ix ON %s USING gist (ll_to_earth(%s, %s));" %
      [table_name, table_name, 'latitude', 'longitude']
  end

  def remove_earthdistance_index table_name
    execute "DROP INDEX %s_earthdistance_ix;" % [table_name]
  end
Run Code Online (Sandbox Code Playgroud)

而且我试图避免每次都将它们粘贴粘贴。有什么方法可以在迁移之间共享代码而无需猴子修补基类?我想找到类似concerns模型的东西。

ruby activerecord raise

4
推荐指数
2
解决办法
419
查看次数

访问rails 3迁移中的自定义帮助程序方法

在rails 2中,我有一个lib/migration_helpers.rb文件,其中包含在db中设置和删除外键的方法.通过添加迁移文件,可以在迁移文件中的self.up和self.down中使用这些方法

require 'migration_helpers'
Run Code Online (Sandbox Code Playgroud)

在顶部,和

extend MigrationHelpers
Run Code Online (Sandbox Code Playgroud)

在课堂陈述后立即.

在rails 3中,这不起作用,如果我尝试使用migration_helpers.rb中的set_foreign_key方法运行迁移,则会引发以下错误:

==  AddFkToArticles: migrating ================================================
-- set_foreign_key("articles", "book_id", "books")
rake aborted!
An error has occurred, this and all later migrations canceled:

undefined method `set_foreign_key' for #<AddFkToArticles:0x000001034a1f38>

Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Run Code Online (Sandbox Code Playgroud)

我已经在config/application.rb中检查过,自动加载路径设置为包含lib.该文件是有效的,因为如果我注释掉require语句,那么rails会对丢失的'migration_helpers'文件抱怨.

我怀疑这是一个范围问题(rails 2使用"def self.up",rails 3使用"def change")但无法想象如何解决问题(现在我只是复制了迁移文件中的代码,只是为了检查它做它应该做的事情).

弗朗切斯科

rails-migrations ruby-on-rails-3

3
推荐指数
1
解决办法
2491
查看次数