【问题标题】:Rails: change models default pathRails:更改模型默认路径
【发布时间】:2013-11-04 20:23:38
【问题描述】:

我的 pb:我有 18 个模型,我想将我的“模型”文件夹拆分为子文件夹。 有没有办法告诉 rails 在子文件夹中查找模型?

【问题讨论】:

    标签: ruby-on-rails configuration


    【解决方案1】:

    是的,这很容易:

    结构:

    app/
      models/
        widgets/
          user_widget.rb
        user.rb
    

    型号:

    class Widgets::UserWidget < ActiveRecord::Base
    end
    
    class User < ActiveRecord::Base
    end
    

    作为记录,它也适用于库:

    结构:

    lib/
      dsl/
        comments_dsl.rb
      tasks/
      graph.rb
    

    类:

    class Graph
    end
    
    class DSL::CommentsDSL
    end
    

    【讨论】:

      【解决方案2】:

      您可以将模型结构如下:

      # /app/models/foo.rb
      class Foo < ActiveRecord::Base
        ..
        has_many :bars, class_name: Foo::Bar
      end
      
      # /app/models/foo/bar.rb
      class Foo::Bar < ActiveRecord::Base
        ..
        belongs_to :foo
      end
      

      您可以通过Foo::Barfoo 通过Foo 访问模型bar。 Rails 会自动加载/app/models 中的所有文件。所以不需要任何必要的配置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-25
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多