【问题标题】:Organizing rails model files into subdirectories将 Rails 模型文件组织到子目录中
【发布时间】:2015-11-09 12:33:47
【问题描述】:

我正在将我的模型组织到下面列出的子目录中。我已经尝试了 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'

config/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

models/blog/post.rb

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

models/blog.rb

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢!我只是想让我的模型井井有条并准备好扩展。如果我的表是单独命名的,那么解耦或移动我的关联会更容易。不过,我对替代品持开放态度。对于组织更大的应用程序有什么建议吗?
    • 这是一个非常开放的问题,答案取决于许多可能未知的约束。对于较大的应用程序,您可能会发现最好将其拆分为通过 API 交换数据的不同应用程序。我建议坚持使用 Rails 约定——作为一种安全措施,避免未来进一步痛苦——并在需求出现时立即调整应用程序,而不是之前。在这种情况下,我只需调用模型Post。如果您有很多 Post 模型,那么我将其命名为 BlogPost 并将表命名为 blog_posts。如果您更喜欢模型的命名空间格式,我仍然会选择blog_posts。我的 2 克拉。
    • 你说得对,它已经开始导致问题:我无法使用该方法生成新帖子。
    • 哈哈哈 :) 好吧,您肯定也能找到解决方法。但这不值得。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多