Ruby-on-Rails : 단일 테이블 상속이있는 모델 생성?
-
05-07-2019 - |
문제
내 시스템에는 몇 가지 모델이 있습니다.
- 사용자 평판
- 명성 후
- 응답 평판
(SO와 유사).
따라서 몇 가지 기본 코드를 공유합니다.
- 값 증분 및 감소
- 평판이 나타내는 세 가지 객체에 속하는 고유 _id (사용자, 게시물, 응답)
C ++가 있다면 "라는 슈퍼 클래스가있을 것입니다.Reputation
"그것은 이러한 개념을 캡슐화 할 것입니다.
현재 별도로 정의 된 세 가지 모델이 있지만 시스템을 구축 할 때 코드 복제 등이 많다는 것을 깨닫기 시작했습니다.
내가 sti를 사용한다면 나는 owner_id
object_id와 a owner_type
.
그렇다면이 사건을 처리하는 가장 좋은 방법은 무엇입니까?
해결책
평판 모델에 고유 한 코드가 있습니까?
그렇지 않다면 당신은 a로 갈 수 있습니다 belongs_to :owner, :polymorphic => true
일반적인 평판 모델에서.
그렇지 않으면 각 서브 모델에서 다음과 같은 _to 호출에 : class_name 인수를 제공 할 수 있어야합니다.
단일 평판 모델에 대한 코드 : (평판 필요 소유자 _ID : 정수 및 소유자 _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
서브 클래스 평판 (평판 테이블 필요 소유자 : 정수 및 유형 : 문자열 열)
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
제휴하지 않습니다 StackOverflow