简体   繁体   English

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

[英]Rails models in subfolders and relationships

I organized some of my rails models in folders which I am autoloading with 我在我自动加载的文件夹中组织了一些我的rails模型

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

I can use all models directly(eg Image.first.file_name ) but when I try to access them through relationships, eg @housing.images.each do... with has_many: images I get the following error 我可以直接使用所有模型(例如Image.first.file_name ),但是当我尝试通过关系访问它们时,例如@housing.images.each do... with has_many: images我得到以下错误

Unable to autoload constant Housing::HousingImage, expected /path/app/models/housing/image.rb to define it

How do i get rails to use my models for the relationship methods? 如何让rails使用我的模型进行关系方法?

I'm running ruby 2.2 and rails 4.2 我正在运行ruby 2.2和rails 4.2

Rails automatically loads models from subfolders but does expect them to have namespace. Rails自动从子文件夹加载模型,但确实希望它们具有命名空间。

/app/models/user.rb
class User
end

/app/models/something/user.rb
class Something::User
end

If you do not properly namespace your models in subfolders it will mess up Rails autoloader and cause errors like you see. 如果你没有在子文件夹中正确地命名模型,它将搞乱Rails自动加载器并导致你看到的错误。

Remove this 删除它

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

And add the proper namespaces to your models and everything will work fine. 并为您的模型添加适当的命名空间,一切都会正常工作。

You can easily use namespaced models in your relationships like this: 您可以在关系中轻松使用命名空间模型,如下所示:

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

user.photos (will be instances of Something::Photo)

If you do not want to use the namespacing but split up your models for other reason, you can do that at the top-level and use other folders next to models. 如果您不想使用命名空间但由于其他原因而拆分模型,则可以在顶层执行此操作并使用模型旁边的其他文件夹。 By default rails loads all the folders in apps, so you could just make a folder "models2" or whatever you want to call it next to "models". 默认情况下,rails会加载应用程序中的所有文件夹,因此您可以在“模型”旁边创建一个文件夹“models2”或任何您想要调用的文件夹。 This will not have any effect on the functionality of the rails class loading. 这对rails类加载的功能没有任何影响。

Given your example you could then do: 根据您的示例,您可以这样做:

/app
  /controllers
  /models
    for all your normal models
  /housing
    for your "housing" models

Like this you can directly access them at the top level namespace, no class_name settings or anything needed. 像这样,您可以直接在顶级命名空间访问它们,没有class_name设置或任何需要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM