任何聲望模型中是否會有任何唯一代碼?
如果不是,您可以通過belongs_to :owner, :polymorphic => true
獲得一個通用的信譽模型。
否則,您應該能夠在每個子模型的belongs_to調用中提供:class_name參數。
代碼單聲譽模型: (聲望需要owner_id:整數和owner_type:字符串列)
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:整數和類型:字符串列)
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
請不要tagspam。你的問題只涉及ruby-on-rails。 – 2009-11-01 20:53:32