在任何信誉模型中是否会有任何唯一代码?
如果没有,您可以使用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