Nested modules in Rails are split into table_name_prefix

I am trying to use nested module / class definitions sequentially in a Rails application, not in the compact ( ::) syntax . However, it does not always load the module file itself, which contains table_name_prefix.

Using Rails 4.1.8 on Ruby 2.1.1 ...

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

This creates app/models/blog.rb:

module Blog
  def self.table_name_prefix
    'blog_'
  end
end

There seem to be many ways to accidentally prevent Rails from automatically loading blog.rb. The simplest example is with helpers.

Change app/helpers/blog/posts_helper.rbto:

module Blog::PostsHelper
end

at

module Blog
  module PostsHelper
  end
end

Start the server, go to /users, and then go to /blog/posts:

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

Similar problems may occur elsewhere, for example, in model tests. This is not limited to assistants.

? blog.rb ?

+4
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.rb module.rb .

monkey-patching ActiveRecord::Base, , ActiveRecord::SchemaMigration, .

0

All Articles