ユーザーがドキュメント、メモ、またはコメントをお気に入りリストに追加できる「お気に入り」機能を備えたアプリケーションがあるとします。
私の心の中で..
- ユーザー
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
(データベースを正しくセットアップするだけです)このデザインは、お気に入りのユースケースの標準です。