我用自定义postgres函数创建了一个迁移:

class CreatePopularityPgFunctions < ActiveRecord::Migration[5.2]
  def up
    execute %{
      CREATE OR REPLACE FUNCTION popularity(count integer, weight integer default 3) RETURNS integer AS $$
        SELECT count * weight
      $$ LANGUAGE SQL IMMUTABLE;
    }
  end

  def down
    execute 'drop function popularity(integer, integer) cascade'
  end
end

运行rake db:migrate可以将其正确地添加到模式中。但是,由于某些原因,运行rake db:reset似乎无法在PG中创建此函数。该函数不在架构中,如果尝试在SQL查询中使用它,则会导致有关缺少函数的错误。

最佳答案

db:reset运行db:drop db:setup。在db:setup中创建数据库架构。但是schema.rb不处理自定义函数或视图。
来自文档:
db/schema.rb无法表示特定于数据库的项,如外键约束、触发器或存储过程。在迁移过程中,可以执行自定义SQL语句,但架构转储程序无法从数据库中重新构造这些语句。如果您使用这样的特性,那么应该将模式格式设置为:sql。
您可以改用structure.sql。使用structure.sql
这在config/application.rb中由config.active_record.schema_格式设置设置,可以是:sql或:ruby。
更多细节here.

关于ruby-on-rails - db:reset之后Postgres函数不持久,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50715188/

10-16 21:48