【问题标题】:Enumerated Types with ActiveRecord and Postgresql使用 ActiveRecord 和 Postgresql 的枚举类型
【发布时间】:2018-01-29 19:48:29
【问题描述】:

我正在关注来自 SitePoint 的 tutorial 将模型属性设置为 Enum 值,Rails 从 4.1 开始支持该值。

我正在尝试添加季节枚举,而不是性别枚举。

这是我在schema.db 中遇到的问题

# Could not dump table "semesters" because of following StandardError
#   Unknown type 'season' for column 'season'

这是我的migration:

class AddSeasonToSemesters < ActiveRecord::Migration[5.1]
  def up
    execute <<-SQL
    CREATE TYPE season AS ENUM ('fall', 'winter', 'spring', 'summer');
    SQL

    add_column :semesters, :season, :season, index: true
  end

  def down
    remove_column :semesters, :season

    execute <<-SQL
    DROP TYPE season;
    SQL
  end
end

还有我的model 文件:

class Semester < ApplicationRecord
  enum season: {
      fall: 'fall',
      winter: 'winter',
      spring: 'spring',
      summer: 'summer'
  }
end

知道我做错了什么吗?任何方向将不胜感激,谢谢。

【问题讨论】:

  • 由于您直接使用 sql 语句,因此请确保您的 config.active_record.schema_format = :sql # default is :ruby 在您的 config/application.rb 中
  • 是的,这是在类似问题中建议的。 stackoverflow.com/a/45430348/4330767 提出了另一种将架构保留在 ruby​​ 中的解决方案,但它似乎没有按预期工作。有什么想法吗?

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

你需要从db/schema.rb切换到db/structure.sql。

根本问题是schema.rb 是 ActiveRecord 看到的数据库结构的表示,但 ActiveRecord 不理解很多东西(例如create type、CHECK 约束和其他出现在 @ 中的东西) 987654327@ 迁移中的语句)PostgreSQL 所做的。你可以create type 随心所欲,但schema.rb 永远不会看到它。

如果你想使用 ActiveRecord 不理解的东西,那么你必须使用db/structure.sql 来存储你的数据库结构。 structure.sql 以数据库理解的方式存储数据库的结构,而不是 ActiveRecord 理解的结构。

切换很简单:

  1. 更新您的 config/application.rb 以包含 config.active_record.schema_format = :sql。
  2. 发送rake db:structure:dump 以获得初始db/structure.sql。
  3. 从目录树和版本控制中删除 db/schema.rb。
  4. 将db/structure.sql 添加到版本控制中。
  5. 调整你的耙子习惯:
    • 使用db:structure:dump 而不是db:schema:dump
    • 使用db:structure:load 而不是db:schema:load

也就是说,我不确定 PostgreSQL 的原生 enum 类型与 ActiveRecord 的交互效果如何,因为我从未做过。 AR's enums 是字符串和整数之间的客户端转换,但 PostgreSQL's enums 在数据库内部处理,它们彼此不知道。可能存在冲突,您需要确保它们彼此同步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多