レールは多くのモデルに属します[閉じた
-
29-09-2019 - |
質問
私は私の質問のようなRails AssociationについてSOについていくつかの質問を見つけましたが、私の人生のために私は使用方法を理解できないようです belongs_to
複数のモデル。
これが次のとおりです テーブル構造 私は持っているつもりです:
User
id
Post
id
user_id #foreign key; a post belongs to a User aka "Who created this post"
Comment
id
user_id #foreign key; a comment belongs to a User aka "Who made this comment"
post_id #foreign key; a comment belongs to a Post aka "What post this comment is for"
そしてその 協会:
User
has_many :posts
has_many :comments
Post
belongs_to :user
has_many :comments
Comment
belongs_to :user
belongs_to :post
これは正しいアプローチですか?
解決
はい、それは正しいアプローチです。
他のヒント
常に「最高の」アプローチではありませんが、Railsは Polymorphic Belonds_to Association. 。 XXX_ID列は多くの可能なテーブルの1つでIDを参照しているのに対し、別の列がそのテーブルのモデルの名前を指定しているため、データベース内の外部キーを定義することを防ぎますが、レールでは関係をより明確にします。また、モデルは、1つ以上のモデルに属するのではなく、他のモデルの1つにのみ属することを制限します。
所属していません StackOverflow