重命名现有的rails模型并添加命名空间

时间:2016-02-25 15:34:45

标签: ruby-on-rails activerecord

原始代码如下:

# 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表。我的设置错过了什么吗?

3 个答案:

答案 0 :(得分:0)

  

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

答案 1 :(得分:0)

  

PG :: UndefinedTable:ERROR:relation&#34; saml_configurations&#34;才不是   存在

默认情况下,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

答案 2 :(得分:0)

如果我让它为我生成一个命名空间模型,我会通过复制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
相关问题