重命名现有轨道模型并添加命名空间



原始代码如下所示:

# app/models/sso_configuration.rb
class SsoConfiguration < ActiveRecord::Base
end
# db/schema.rb
create_table "sso_configurations", force: true do |t|
  ...
end

必须重命名模型并添加命名空间,以便我有Sso::SamlConfiguration.我更改了模型和数据库表。

# db/migrate20160225144615_rename_sso_configurations_to_sso_saml_configurations.rb
class RenameSsoConfigurationsToSsoSamlConfigurations < ActiveRecord::Migration
  def change
    rename_table :sso_configurations, :sso_saml_configurations
  end
end
# db/schema.rb
create_table "sso_saml_configurations", force: true do |t|
  ...
end
# app/models/sso/saml_configuration.rb
module Sso
  class SamlConfiguration < ActiveRecord::Base
  end
end

当我打开 rails 控制台时,会发生以下情况。

> Sso::SamlConfiguration
=> Sso::SamlConfiguration(Table doesn't exist)
> Sso::SamlConfiguration.new
=> PG::UndefinedTable: ERROR:  relation "saml_configurations" does not exist

我最初的想法是,按照惯例,命名空间模型应该将蛇壳名称作为表名,这样Foo::Bar应该有一个相应的foo_bars表。我的设置是否缺少某些内容?

rename_table :sso_configurations, :sso_saml_configurations

当您尝试执行此操作时,将暗示此SsoSamlConfiguration.all Sso::SamlConfiguration.all

只需回滚迁移并更改此行

rename_table :sso_configurations, :sso_saml_configurations

对此

rename_table :sso_configurations, :saml_configurations

现在这应该可以工作

Sso::SamlConfiguration.all
PG::

未定义表:错误:关系"saml_configurations"不 存在

默认情况下,Rails 会查找名称为模型复名称的表,即在您的情况下,它会查找saml_configurations,因为模型名称为 saml_configuration

您需要使用 self.table_name 将模型显式映射到其他表

# app/models/sso/saml_configuration.rb
module Sso
  class SamlConfiguration < ActiveRecord::Base
    self.table_name = "sso_saml_configurations"
  end
end
我通过

复制 rails 如果我让它为我生成命名空间模型会做什么来找出解决方案。

rails g model sso/test
invoke  active_record
create    db/migrate/20160226074853_create_sso_tests.rb
create    app/models/sso/test.rb
create    app/models/sso.rb
invoke    rspec
create      spec/models/sso/test_spec.rb
invoke      factory_girl
create        spec/factories/sso_tests.rb

我检查了这些新文件中的所有路径和名称约定,唯一错过的是文件app/models/sso.rb

创建以下内容解决了我的问题:

# app/models/sso.rb
module Sso
  def self.table_name_prefix
    'sso_'
  end
end

然后

rails d model sso/test

最新更新