ruby-on-rails – 将类分成Ruby on Rails中的多个文件
发布时间:2020-12-16 21:28:48 所属栏目:百科 来源:网络整理
导读:我试图将大型模型分成多个文件进行逻辑组织.所以我有两个文件: model1.rb class Model1 ActiveRecord::Base before_destroy :destroying has_many :things,:dependent=:destroy def method1 ... end def method2 ... endendrequire 'model1_section1' model
我试图将大型模型分成多个文件进行逻辑组织.所以我有两个文件:
model1.rb class Model1 < ActiveRecord::Base before_destroy :destroying has_many :things,:dependent=>:destroy def method1 ... end def method2 ... end end require 'model1_section1' model1_section1.rb class Model1 def method3 ... end def self.class_method4 ... end end 但是当应用程序加载时,并且有一个对Model1.class_method4的调用,我得到: undefined method `class_method4' for #<Class:0x92534d0> 我也试过这个要求: require File.join(File.dirname(__FILE__),'model1_section1') 我在这里做错了什么? 解决方法
我知道我稍晚回答这个问题,但是我刚才在我的一个应用程序中做了这个,所以以为我会发布我使用的解决方案.
让我们这是我的模特儿: class Model1 < ActiveRecord::Base # Stuff you'd like to keep in here before_destroy :destroying has_many :things,:dependent => :destroy def method1 end def method2 end # Stuff you'd like to extract before_create :to_creation_stuff scope :really_great_ones,#... def method3 end def method4 end end 您可以将其重构为: # app/models/model1.rb require 'app/models/model1_mixins/extra_stuff' class Model1 < ActiveRecord::Base include Model1Mixins::ExtraStuff # Stuff you'd like to keep in here before_destroy :destroying has_many :things,:dependent => :destroy def method1 end def method2 end end 和: # app/models/model1_mixins/extra_stuff.rb module Model1Mixins::ExtraStuff extend ActiveSupport::Concern included do before_create :to_creation_stuff scope :really_great_ones,#... end def method3 end def method4 end end 它的工作完美感谢ActiveSupport :: Concern给你的额外清洁.希望能解决这个老问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Cocos2d-x tinyxml2用于xml的解析,自动生成xml文件和解析xm
- node ajax post请求 服务器端报错413 (payload too large)
- 为什么react-router正确处理正则表达式`path`,但同时抛出错
- Cocos开发中性能优化工具介绍之Visual Studio内存泄漏检测工
- Flex 利用ActionScript接口实现Module模块间的数据通信
- cisco交换机端口聚合、VTP、ACL配置实例
- 用正则判断一个字符串是否包含中文
- 使用Oracle存储过程向表中写入、更新和删除数据
- React 教程第十四篇 —— Redux 跨组件通信高级篇之中间件
- c# – DataGridView行添加事件