--- title: 12th 鐵人賽 Day_14 model 關聯性 多對多? & 部落格分類系統 tags: 12th 鐵人賽 --- # 12th 鐵人賽 Day_14 model 關聯性 多對多? & 部落格分類系統 嗨!各位朋友大家好,打給後,歹嘎吼,胎尬喉,我是阿圓,一樣有請今天的one piece: ![](https://i.imgur.com/JTKLWPm.png) # model 關聯性 多對多? 昨天說完了一對多,接著要來說一下多對多的部分,一樣來個舉例: 在學校裡,一個班級會有很多個任教的老師,一個老師可以任教很多個班級,而確認哪個老師教哪個班級,會需要藉由課表來記錄。 昨天有講到, Rails 是以分上下屬的方式去實作 model 關聯性,若要變成多對多,則需要第三方的 modle 來幫忙做紀錄,也就是上面說的課表。 課表中會有兩個欄位,記錄老師的編號以及班級的編號。 ```ruby= class Curriculum < ActiveRecord belongs_to :teacher belongs_to :schoolclass end class Teacher < ActiveRecord has_many :schoolclasses, through :curriculums end class SchoolClass < ActiveRecord::Base has_many :teachers, through :curriculums end ``` 像這樣,設定的話,teacher跟schoolclass,就可以透過curriculum這個資料表存取到彼此,並互相擁有昨天說到的has_many方法: ```ruby= teacher1 = Teacher.first schoolclass1 = Schoolclass.first # =====================# teacher1.Schoolclass #列出 teacher1 的所有 Schoolclass schoolclass1.teacher #列出 schoolclass1 的所有 teacher ``` (其他的就都不贅述啦,可以翻我前一天~) 若仔細觀察 console 裡的資訊,當寫下`teacher1.Schoolclass`,其實是會去 curriculums 這個資料表裡面撈東西的! 至於has_many 後面有什麼方式可以做設定,請先參考[官方文件](https://guides.rubyonrails.org/association_basics.html),明天就讓我來整理整理! # 部落格實作 ## 貼文分類系統 我們要從部落格的分類功能開始切入了,其實就是要增加一個 category 的 controller 及 model 1. 新增 category controller 2. 增加 category 的 routes 3. 增加 category controller 的 action 4. 增加 category 的 model `rails g model Category name` 接著來增加關聯,一篇文章上面有很多分類,而這個分類又會有很多的文章。 所以我們來增加第三方 model : `rails g model Posts_categories post:references category:references` 此時來看看,這個 model: ```ruby= class PostsCategory < ApplicationRecord belongs_to :post belongs_to :category end ``` 目前資料表的關聯是: ![](https://i.imgur.com/2mzBPqf.png) 接著去分別去 post 、 category 的 model ```ruby= class Post < ActiveRecord has_many :category, through :post_categories end ``` ```ruby= class Category < ActiveRecord has_many :posts, through :post_categories end ``` 此時的 model 關聯是: ![](https://i.imgur.com/N6BEf0O.png) 這樣的話,在頁面中想要用分類來顯示出文章的話,只要使用: ```ruby= categoy1 = Categoy.create(name:'ruby') category1.posts ``` 就可以囉~ 感謝各位看到這邊,若有任何建議,請各位不吝指教!我們明天見! ![](https://i.imgur.com/PPbpd2b.gif)