Rails模型中的子文件夹和关系 [英] Rails models in subfolders and relationships

查看:149
本文介绍了Rails模型中的子文件夹和关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我安排我的一些轨道模型的文件夹,我正与

I organized some of my rails models in folders which I am autoloading with

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

我可以直接使用所有型号(如 Image.first.file_name ),但是当我通过关系,如对其进行访问 @ housing.images.each DO ... 的has_many:图片我收到以下错误

I can use all models directly(e.g Image.first.file_name) but when I try to access them through relationships, e.g. @housing.images.each do... with has_many: images I get the following error

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?

我运行红宝石2.2和4.2轨

I'm running ruby 2.2 and rails 4.2

推荐答案

从Rails的子文件夹会自动加载模式,但并希望他们能有空间。

Rails automatically loads models from subfolders but does expect them to have namespace.

/app/models/user.rb
class User
end

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

如果您不正确命名空间的车型在子文件夹就像你看到它会搞砸了Rails的自动加载磁带机和导致错误。

If you do not properly namespace your models in subfolders it will mess up Rails autoloader and cause errors like you see.

删除此

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)

如果你不想使用命名空间,但分手了你的模型为其他原因,你可以这样做,在顶层和使用其他文件夹旁边的机型。 默认情况下轨负荷应用程序的所有文件夹,这样你就可以只让一个文件夹models2或者随便你怎么称呼它旁边的模特。 这不会对导轨类装载的功能性的任何影响。

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". This will not have any effect on the functionality of the rails class loading.

鉴于你例如,你可以再做:

Given your example you could then do:

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

这样你可以在顶级命名空间中直接访问它们,不需要设置将class_name或任何东西。

Like this you can directly access them at the top level namespace, no class_name settings or anything needed.

这篇关于Rails模型中的子文件夹和关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆