【发布时间】:2015-08-31 15:45:52
【问题描述】:
首先,继承方法可能不正确。如果是这样,请解释另一种方法。
这是一个设置示例。
除了使用完全相同的数据库之外,我还有许多未连接的应用程序。为了使代码库枯竭,我有一个包含所有活动记录类的引擎。我想在主要应用程序中保留应用程序特定的范围和方法。
在我的 Rails 引擎中,
class MyEngine::User < ActiveRecord::Base
has_many :dogs
end
class MyEngine::Dog < ActiveRecord::Base
belongs_to :user
end
在我的主应用中,
class User < MyEngine::User
end
class Dog < MyEngine::Dog
# EDITED TO SHOW EXAMPLE OF HOW SCOPE DOESN'T BELONG IN ENGINE
DOGS_WITH_SPOTS_IDS = [ 1, 2, 3, 4 ]
scope :with_spots, -> { where(id: DOGS_WITH_SPOTS_IDS) }
end
我的主应用程序中的问题,
user = User.last
user.dogs
# => #<ActiveRecord::Associations::CollectionProxy[#<MyEngine::Dog spots: true>]>
user.dogs.with_spots
NoMethodError: undefined method 'with_spots' for #<MyEngine::Dog::ActiveRecord_Association_CollectionProxy:0x007fa4bf838e50>
虽然这可行
class User < MyEngine::User
has_many :dogs
end
我不希望重新定义/定义主应用程序中的所有关联。
这种类型的问题只会在我所有的主要应用程序中以不同的形式出现。这让我想到可能有办法重新定义关联。
有没有一种方法可以评估子类而不是超类的关联,就像 STI 模式一样,让 Rails 助手识别不同的子类?
意思是,我希望我的主应用 User#dogs 返回主应用 Dog 而不是 MyEngine::Dog。
# may not be the exact code, just off the top of my head
instance_eval do
def model_name
self.class.name
end
end
【问题讨论】:
标签: ruby ruby-on-rails-4 activerecord associations metaprogramming