Rails模型在子文件夹和关系中

Ren*_*ler 7 ruby activerecord ruby-on-rails ruby-on-rails-4

我在我自动加载的文件夹中组织了一些我的rails模型

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
Run Code Online (Sandbox Code Playgroud)

我可以直接使用所有模型(例如Image.first.file_name),但是当我通过关系来访问它们,例如,@housing.images.each do...has_many: images我得到以下错误

Unable to autoload constant Housing::HousingImage, expected /path/app/models/housing/image.rb to define it
Run Code Online (Sandbox Code Playgroud)

如何让rails使用我的模型进行关系方法?

我正在运行ruby 2.2和rails 4.2

max*_*igs 9

Rails自动从子文件夹加载模型,但确实希望它们具有命名空间.

/app/models/user.rb
class User
end

/app/models/something/user.rb
class Something::User
end
Run Code Online (Sandbox Code Playgroud)

如果你没有在子文件夹中正确地命名模型,它将搞乱Rails自动加载器并导致你看到的错误.

删除它

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
Run Code Online (Sandbox Code Playgroud)

并为您的模型添加适当的命名空间,一切都会正常工作.

您可以在关系中轻松使用命名空间模型,如下所示:

class User
  has_many :photos, class_name: 'Something::Photo'
end

user.photos (will be instances of Something::Photo)
Run Code Online (Sandbox Code Playgroud)

如果您不想使用命名空间但由于其他原因而拆分模型,则可以在顶层执行此操作并使用模型旁边的其他文件夹.默认情况下,rails会加载应用程序中的所有文件夹,因此您可以在"模型"旁边创建一个文件夹"models2"或任何您想要调用的文件夹.这对rails类加载的功能没有任何影响.

根据您的示例,您可以这样做:

/app
  /controllers
  /models
    for all your normal models
  /housing
    for your "housing" models
Run Code Online (Sandbox Code Playgroud)

像这样你可以直接在顶级命名空间访问它们,没有class_name设置或任何需要的东西.

  • 正确,但我不会将它们命名为命名空间,这就是我首先添加配置的原因。我还尝试了带有非命名空间类名的 class_name 选项,但它也不起作用。 (2认同)