以下是我遇到的问题: https://gist.github.com/1003813
或
假设您有派生类:
class User < ActiveRecord::Base
include ThisThing
include ThatThing
[...]
end
class OurUser < User
set_table_name 'users'
[...]
end
我需要一些关联,例如:
belongs_to :friend,
:class_name => 'User',
:foreign_key => :friend_of
问题在于,如果在User类中声明了这一点,则OurUser的朋友将是User,并且不会包含OurUser中包含的任何额外方法。当然,在编写User类时,您并不知道正确的类名。
我需要一些关于我如何做到这一点的建议,以便OurUser将有一个正确类的朋友
答案 0 :(得分:0)
创建一个包含所有共享行为的模块,并使用Module#included钩子在include中动态定义关联。即:
module SharedBehaviour
def self.included(base)
base.class_eval do
set_table_name 'users'
belongs_to :friend, :class_name => base.name, :foreign_key => :friend_of
include ThisThing
include ThatThing
# other class method calls go here (validations, etc)
end
end
module ClassMethods
# shared class methods go here
end
# shared instance methods go here
end
class User < ActiveRecord::Base
inclde SharedBehaviour
end
class OtherUser < ActiveRecord::Base
include SharedBehaviour
end