I'm trying to split a large model into multiple files for logical organization. So i have two files:
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
but when the app loads, and there is a call to Model1.class_method4, i get:
undefined method `class_method4' for #<Class:0x92534d0>
i've also tried this for the require:
require File.join(File.dirname(__FILE__), 'model1_section1')
What am i doing wrong here?
I know I'm answering this a little late, but I've just done this in one of my apps so thought I'd post the solution I used.
Let's this was my model:
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
You can refactor it to:
# 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
and:
# 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
It works perfectly thanks to the extra cleanliness that ActiveSupport::Concern
gives you. Hope this solves this old question.
Here's an article that does a good job of proposing solutions to this problem:
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With