【问题标题】:Nested modules in Rails breaking table_name_prefixRails 中的嵌套模块破坏了 table_name_prefix
【发布时间】:2015-02-13 12:54:49
【问题描述】:

我试图在 Rails 应用程序中一致地使用嵌套的模块/类定义,而不是紧凑的 (::) 语法。但是,它并不总是加载包含table_name_prefix 的模块文件本身。

在 Ruby 2.1.1 上使用 Rails 4.1.8...

rails new my_app
...
rails g scaffold User
rails g scaffold Blog::Post

这会创建app/models/blog.rb:

module Blog
  def self.table_name_prefix
    'blog_'
  end
end

似乎有很多方法可以意外阻止 Rails 自动加载 blog.rb。最简单的例子是通过助手。

app/helpers/blog/posts_helper.rb 更改为:

module Blog::PostsHelper
end

到:

module Blog
  module PostsHelper
  end
end

启动服务器,访问/users,然后访问/blog/posts

SQLite3::SQLException: no such table: posts: SELECT "posts".* FROM "posts"

在其他地方也可能出现类似问题,例如在模型测试中。它不仅限于助手。

解决此问题的最佳方法是什么?显式加载 blog.rb 和任何其他命名空间模块?

【问题讨论】:

  • 我能够重现该问题 - 感谢 Anthony。我会在 github 上创建一个问题,看看团队怎么说。
  • 也许...虽然我更多的是寻找确保blog.rb 被加载的最佳方法,而不是建议对Rails 进行更改。这显然不是很多人遇到的问题......

标签: ruby-on-rails ruby namespaces


【解决方案1】:

一种不依赖自动加载的解决方案是将模型设置为从以下继承,而不是直接从ActiveRecord::Base 继承:

class CustomActiveRecordBase < ActiveRecord::Base
  self.abstract_class = true

  # If no table name prefix has been defined, include the namespace/module as
  # table name prefix, e.g., Blog:: -> blog_
  def self.table_name
    # If a table_name_prefix has been defined, follow default behaviour
    return super if full_table_name_prefix.present?

    # Find the prefix, e.g., Blog::Post -> 'blog', User -> ''
    prefix = model_name.name.deconstantize.underscore

    # If no prefix, follow default behaviour
    return super unless prefix.present?

    # Otherwise add the prefix with an underscore
    "#{prefix}_#{super}"
  end
end

那么self.table_name_prefix就不用在blog.rb中定义了。

这些可以通过lib/templates/active_record/model/model.rbmodule.rb 中的适当文件设置为未来模型的默认值,基于the default active record templates

可以全部通过猴子补丁ActiveRecord::Base来完成,但这会干扰其他类,例如ActiveRecord::SchemaMigration,它没有表前缀。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多