ruby-on-rails:単一のテーブル継承でモデルを作成しますか?

StackOverflow https://stackoverflow.com/questions/1611378

  •  05-07-2019
  •  | 
  •  

質問

システムにいくつかのモデルがあります:

  • ユーザーの評判
  • 評判の投稿
  • 応答の評判

(SOと同様)。

だから、彼らはいくつかの基本的なコードを共有しています:

  • 値の増分および減分
  • レピュテーションが表す3つのオブジェクト(User、Post、Response)に属するunique_id

C ++がある場合、" 評判"というスーパークラスがあります。それはこれらの概念をカプセル化します。

現在、別々に定義された3つのモデルがありますが、システムを構築するにつれて、コードの重複などがたくさんあることに気付き始めています。

STIを使用する場合、object_idと owner_type である owner_id フィールドが必要です。

では、このケースを処理する最良の方法は何ですか?

役に立ちましたか?

解決

レピュテーションモデルのいずれかに一意のコードはありますか?

そうでない場合は、 belongs_to:owner、:polymorphic =>で取得できます。一般的な評判モデルではtrue

それ以外の場合は、各サブモデルの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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top