我的系统中有几个模型:
- 用户声誉
- 发表声誉
- 响应声誉
(类似于 SO)。
因此,他们共享一些基本代码:
- 递增和递减值
- 属于信誉所代表的三个对象(用户、帖子、响应)的 unique_id
如果有 C++,我会有一个名为“ Reputation”的超类来封装这些概念。
目前,我有三个模型,分别定义但当我构建系统时,我开始意识到有很多代码重复等。
如果我要使用 STI,那么我将不得不使用owner_idobject_id 和owner_type.
那么,处理这种情况的最佳方法是什么?
我的系统中有几个模型:
(类似于 SO)。
因此,他们共享一些基本代码:
如果有 C++,我会有一个名为“ Reputation”的超类来封装这些概念。
目前,我有三个模型,分别定义但当我构建系统时,我开始意识到有很多代码重复等。
如果我要使用 STI,那么我将不得不使用owner_idobject_id 和owner_type.
那么,处理这种情况的最佳方法是什么?
在任何信誉模型中是否会有任何唯一代码?
如果没有,您可以使用belongs_to :owner, :polymorphic => true通用的 Reputation 模型。
否则,您应该能够在每个子模型的 belongs_to 调用中提供 :class_name 参数。
单一信誉模型的代码:(信誉需要 owner_id:integer 和 owner_type:string 列)
class Reputation < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
...
end
class User < ActiveRecord::Base
has_one :reputation, :as => :owner
end
class Post < ActiveRecord::Base
has_one :reputation, :as => :owner
end
class Response < ActiveRecord::Base
has_one :reputation, :as => :owner
end
子类化声誉(声誉表需要 owner_id:integer 和 type:string 列)
class Reputation < ActiveRecord::Base
...
end
class UserReputation < Reputation
belongs_to :owner, :class_name => "User"
...
end
class PostReputation < Reputation
belongs_to :owner, :class_name => "Post"
...
end
class ResponseReputation < Reputation
belongs_to :owner, :class_name => "Response"
...
end
class User < ActiveRecord::Base
has_one :user_reputation, :foreign_key => :owner_id
...
end
class Post < ActiveRecord::Base
has_one :post_reputation, :foreign_key => :owner_id
...
end
class Response < ActiveRecord::Base
has_one :response_reputation, :foreign_key => :owner_id
...
end