ruby-on-rails – 子文件夹和关系中的Rails模型
发布时间:2020-12-16 23:06:10 所属栏目:百科 来源:网络整理
导读:我在我自动加载的文件夹中组织了一些我的rails模型 config.autoload_paths += Dir[Rails.root.join('app','models','{**}')] 我可以直接使用所有模型(例如Image.first.file_name),但是当我尝试通过关系访问它们时,例如@ housing.images.each do … with has_
我在我自动加载的文件夹中组织了一些我的rails模型
config.autoload_paths += Dir[Rails.root.join('app','models','{**}')] 我可以直接使用所有模型(例如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 如何让rails使用我的模型进行关系方法? 我正在运行ruby 2.2和rails 4.2 解决方法
Rails自动从子文件夹加载模型,但确实希望它们具有命名空间.
/app/models/user.rb class User end /app/models/something/user.rb class Something::User end 如果你没有在子文件夹中正确地命名模型,它将搞乱Rails自动加载器并导致你看到的错误. 删除它 config.autoload_paths += Dir[Rails.root.join('app','{**}')] 并为您的模型添加适当的命名空间,一切都会正常工作. 您可以在关系中轻松使用命名空间模型,如下所示: class User has_many :photos,class_name: 'Something::Photo' end user.photos (will be instances of Something::Photo) 如果您不想使用命名空间但由于其他原因而拆分模型,则可以在顶层执行此操作并使用模型旁边的其他文件夹. 根据您的示例,您可以这样做: /app /controllers /models for all your normal models /housing for your "housing" models 像这样你可以直接在顶级命名空间访问它们,没有class_name设置或任何需要的东西. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |