gpt4 book ai didi

ruby-on-rails - 在 Ruby on Rails 中将一个类拆分为多个文件

转载 作者:行者123 更新时间:2023-12-03 23:34:33 25 4
gpt4 key购买 nike

我正在尝试将大型模型拆分为多个文件以进行逻辑组织。所以我有两个文件:

模型1.rb

class Model1 < ActiveRecord::Base
before_destroy :destroying
has_many :things, :dependent=>:destroy

def method1
...
end
def method2
...
end

end
require 'model1_section1'

模型1_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 的额外清洁度,它可以完美运行。给你。希望这能解决这个老问题。

关于ruby-on-rails - 在 Ruby on Rails 中将一个类拆分为多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5241527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com