ユーザーがドキュメント、メモ、またはコメントをお気に入りリストに追加できる「お気に入り」機能を備えたアプリケーションがあるとします。
私の心の中で..
- ユーザー
has_many
のお気に入り belongs_to
ユーザーをお気に入りにする
- お気に入りを記録
belongs_to
する belongs_to
お気に入りに注意belongs_to
お気に入りにコメントする
このタイプの関連付けの問題は何ですか?また、ポリモーフィックな関連付けはどのように役立ちますか?
ユーザーがドキュメント、メモ、またはコメントをお気に入りリストに追加できる「お気に入り」機能を備えたアプリケーションがあるとします。
私の心の中で..
has_many
のお気に入りbelongs_to
ユーザーをお気に入りにするbelongs_to
するbelongs_to
お気に入りに注意belongs_to
お気に入りにコメントするこのタイプの関連付けの問題は何ですか?また、ポリモーフィックな関連付けはどのように役立ちますか?
あなたの Favorite インスタンスは、それが何を優先しているのかわからないからです:)それは it だけhas_one :note
でなく、 has_one :comment
、または? しかし、確かに両方ではありません。
ポリモーフィック アソシエーション 反対の方法Favorite
は、オブジェクトが属する:favorited
オブジェクトがポリモーフィックであることを表すので、その名前が文字列 db 列に格納される任意のクラスであることを表すため、役立ちます:favorited_type
。そのため、お気に入りのオブジェクトは、それがメモまたはドキュメントを優先することを認識します。またはコメント。
いくつかのコードで
class Note
has_many :favorites, :as => :favorited
has_many :fans, :through => :favorites, :source => :user
end
class Discussion
has_many :favorites, :as => :favorited
has_many :fans, :through => :favorites, :source => :user
end
class Comment
has_many :favorites, :as => :favorited
has_many :fans, :through => :favorites, :source => :user
end
class Favorite
belongs_to :user
belongs_to :favorited, :polymorphic => true # note direction of polymorphy
end
class User
has_many :favorites
has_many :favorite_notes, :through => :favorites, :source => favorited, :source_type => "Note"
has_many :favorite_comments, :through => :favorites, :source => favorited, :source_type => "Comment"
has_many :favorite_discussions, :through => :favorites, :source => favorited, :source_type => "Discussion"
end
(データベースを正しくセットアップするだけです)このデザインは、お気に入りのユースケースの標準です。