ila*_*sno 13 model ruby-on-rails
我正在尝试将大型模型拆分为多个文件以进行逻辑组织.所以我有两个文件:
model1.rb
class Model1 < ActiveRecord::Base
before_destroy :destroying
has_many :things, :dependent=>:destroy
def method1
...
end
def method2
...
end
end
require 'model1_section1'
Run Code Online (Sandbox Code Playgroud)
model1_section1.rb
class Model1
def method3
...
end
def self.class_method4
...
end
end
Run Code Online (Sandbox Code Playgroud)
但是当应用程序加载,并且调用Model1.class_method4时,我得到:
undefined method `class_method4' for #<Class:0x92534d0>
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个要求:
require File.join(File.dirname(__FILE__), 'model1_section1')
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
我知道我有点迟到了,但我刚刚在我的一个应用程序中做了这个,所以我想发布我使用过的解决方案.
我们这是我的模特:
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
Run Code Online (Sandbox Code Playgroud)
你可以将它重构为:
# 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
Run Code Online (Sandbox Code Playgroud)
和:
# 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
Run Code Online (Sandbox Code Playgroud)
由于额外的清洁度,它完美地运作ActiveSupport::Concern.希望这能解决这个老问题.
| 归档时间: |
|
| 查看次数: |
8220 次 |
| 最近记录: |