[Rails][polymorphic]多型關聯

林班尼
Jan 6, 2021

--

若要在多個model下建立 一個共用的 model

例如現有的 topics, posts, pictures 都要有留言的功能

除了專屬自己的table外

topics -> topic_comments

posts -> post_comments

pictures -> picture_comments

可以利用rails 中 的 polymorphic [多型關聯]

rails g model comment

#migrate/create_comments.rb

新增 t.references :commentable, polymorphic: true, index: true

或是

t.integer :commentable_id

t.string :commentable_type

然後在

#mode/comment.rb

宣告

belongs_to :commentable, polymorphic: true

並在需要關聯的model 中

#model/topic.rb

宣告

has_many :comments, as: :commentable

若使用 Topic.comments.create(content: “Hi”)

在rails consile 查看可以看到

commentable_type: “Topic”, commentable_id: 1,

的關聯訊息

--

--

No responses yet