2

Rails 関連ガイドを読んでいますが、これが正しく行われているかどうかはまだわかりません。

私のアプリにはユーザーと製品があります。

ユーザーは、それらの製品に関するコメント、レビュー、および写真を投稿できます。

Contributions という結合モデルを作成することにしました。

  belongs_to :user
  belongs_to :building
  belongs_to :contributable, polymorphic: true

そして、ユーザーの場合:

has_many :contributions, as: contributable
has_many :products, through: contributions

製品:

has_many :contributions, as: contributable
has_many :users, through: contributions

次に、たとえば、私の Review モデルでは次のようになります。

belongs_to :user
belongs_to :product

私はこれを正しくやっているような気がしません。基本的に、コントリビューションには常に製品とユーザーが関連付けられている必要がありますが、コントリビューションにはレビュー、コメント、または写真のいずれかを含めることができるようにしたいと考えています。

ポリモーフィックな関連付けを持つ結合テーブルは、ここに行く正しい方法ですか?

4

1 に答える 1

4

このようなものがあなたが探しているものだと思います。

class User < ActiveRecord::Base
  has_many :contributions
end

class Product < ActiveRecord::Base
  has_many :contributions
end

class Contribution < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
  belongs_to :contributable, :polymorphic => true
end

class Comment < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

class Review < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

class Photo < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

テーブルにcontributable_idcontributable_typeフィールドがあることを確認してください。contributions

于 2013-05-25T21:40:17.887 に答える