相关疑难解决方法(0)

Rails - 抽象类定义和文件命名的最佳实践

我想定义3个类:

  • a MotherClass(摘要,无法推断)
  • a SubClassA(继承自MotherClass)
  • a SubClassB(继承自MotherClass)

在Rails中声明它的最佳解决方案是什么?

1.将所有内容放入app/models /

  • MotherClass < AR::Base 在app/models/mother_class.rb中
  • SubClassA < MotherClass 在app_models/sub_class_a.rb中
  • SubClassB < MotherClass 在app/models/sub_class_b.rb中

优点:实施起来并不复杂

不方便:模型文件夹中的大混乱

2.为两个子类创建一个模块

  • MotherClass < AR::Base 在app/models/mother_class.rb中
  • MotherModule::SubClassA < MotherClass 在app/models/mother_module/sub_class_a.rb中
  • MotherModule::SubClassB < MotherClass 在app/models/mother_module/sub_class_b.rb中

优点:与解决方案1相同

不方便:命名MotherModuleMotherClass使用不同的名称,但它们的意思几乎相同

3.为3个类创建一个模块

  • MotherModule::Base < AR::Base 在app/models/mother_module/base.rb中
  • MotherModule::SubClassA < MotherModule::Base 在app/models/mother_module/sub_class_a.rb中
  • MotherModule::SubClassB < MotherModule::Base 在app/models/mother_module/sub_class_b.rb中

优点:非常干净

不方便:需要一些函数Base来覆盖(例如table_name)


所以我的问题是:Rails中的最佳实践是什么? - 如何命名我的课程? - 他们的目录是什么?

abstract-class model ruby-on-rails

13
推荐指数
1
解决办法
1万
查看次数

Rails的自动加载/恒定分辨率正在创建ghost模块

这是一个全新的Rails 5.1.4应用程序,带有模型和几个路由和控制器.

命名空间控制器引用顶级模型:

class AdminArea::WelcomeController < ApplicationController
  def index
    @user = User.new(name: 'Sergio')
  end
end
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.您可以查看主人,导航到http://localhost:3000/admin_area/welcome并查看它是否有效.

但如果我们要添加一个空目录app/presenters/admin_area/user/*,那么事情会变得奇怪.突然之间,User那个控制器不是我的模型,而是一个不存在的模块!

NoMethodError (undefined method `new' for AdminArea::User:Module):

app/controllers/admin_area/welcome_controller.rb:3:in `index'
Run Code Online (Sandbox Code Playgroud)

当然,该模块没有任何[非内置]方法,也无法固定到磁盘上的源文件中.

问题:为什么添加一个空目录导致rails无法通过空气神秘地召唤模块,而不是正确地将名称解析User为我的模型?


*实际上,如果您按原样检查该分支,您将收到不同的错误.

NameError(未初始化的常量AdminArea :: WelcomeController :: User)

因为git不会让我提交一个空目录,所以我.keep在那里添加了一个文件.但是一旦删除该文件,就会得到上述行为.

ruby-on-rails

7
推荐指数
1
解决办法
208
查看次数

Rails 3.2.9和子文件夹中的模型

自rails 3.2.9以来,我无法在子文件夹中存储模型.在我的应用程序中,我有这棵树:

models
 -type_models
 -assets
 -user
 -concerns
Run Code Online (Sandbox Code Playgroud)

也在application.rb中

config.autoload_paths += Dir["#{config.root}/app/models/*"]
Run Code Online (Sandbox Code Playgroud)

所有东西都没问题,直到3.2.9.现在我有"未知常量"错误.我不想命名大量模型并修复所有应用程序以使用命名空间模型.

Warning: Error loading /var/www/my_app/app/models/type_models/context_type.rb:
uninitialized constant TypeModels::ContextType
Run Code Online (Sandbox Code Playgroud)

file context_type.rb:

class ContextType ... end
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails loading

5
推荐指数
1
解决办法
1375
查看次数

标签 统计

ruby-on-rails ×3

abstract-class ×1

loading ×1

model ×1