将rails模型文件组织到子目录中

时间:2015-08-16 23:05:17

标签: ruby-on-rails ruby-on-rails-4 design-patterns model subdirectory

我正在将我的模型组织到子目录中,如下所示。我已经尝试过StackOverflow中列出的每个解决方案以及其他一些不断出错的解决方案。看似简单的任务,需要帮助。

Makandra - Organizing Large Rails apps

Rails 4: organize rails models in sub path without namespacing models?

How to organize Rails models that are too fat?

Rails models in subfolders and relationships

但是,我一直收到此错误:

  

ActiveRecord :: StatementInvalid:找不到表'blog_posts'

配置/ application.rb中:

  1 require File.expand_path('../boot', __FILE__)
  2 
  3 require 'rails/all'
  4 
  5 # Require the gems listed in Gemfile, including any gems
  6 # you've limited to :test, :development, or :production.
  7 Bundler.require(*Rails.groups)
  8 
  9 module Multifile
 10   class Application < Rails::Application
 11     # Settings in config/environments/* take precedence over those specified here.
 12     # Application configuration should go into files in config/initializers
 13     # -- all .rb files in that directory are automatically loaded.
 14 
 15     # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
 16     # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
 17     # config.time_zone = 'Central Time (US & Canada)'
 18 
 19     # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
 20     # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
 21     # config.i18n.default_locale = :de
 22 
 23     # Do not swallow errors in after_commit/after_rollback callbacks.
 24     config.active_record.raise_in_transactional_callbacks = true
 25   end
 26 end

文件:

app/models
├── blog
│   └── post.rb
├── blog.rb
└── concerns

路线:

 3   resources :blogs do
 4     resources :posts
 5   end

模型/博客/ post.rb

 13 class Blog::Post < ActiveRecord::Base 
 14   belongs_to :blog
 15 end

模型/ blog.rb

 11 class Blog < ActiveRecord::Base
 12   has_many :posts
 13 end

1 个答案:

答案 0 :(得分:2)

名为Blog::Post的模型的表名称的Rails约定为blog_posts。您可以通过在模型上设置.table_name来覆盖它:

class Blog::Post < ActiveRecord::Base 
  self.table_name = "posts"
end

无论如何,我建议尽可能遵循Rails惯例。是否有理由不为您的表blog_posts命名?