iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0
自我挑戰組

Ruby on Rails 新手的30個問題!系列 第 14

Day_14 model 關聯性 多對多? & 部落格分類系統

嗨!各位朋友大家好,打給後,歹嘎吼,胎尬喉,我是阿圓,一樣有請今天的one piece:

model 關聯性 多對多?

昨天說完了一對多,接著要來說一下多對多的部分,一樣來個舉例:

在學校裡,一個班級會有很多個任教的老師,一個老師可以任教很多個班級,而確認哪個老師教哪個班級,會需要藉由課表來記錄。

昨天有講到, Rails 是以分上下屬的方式去實作 model 關聯性,若要變成多對多,則需要第三方的 modle 來幫忙做紀錄,也就是上面說的課表。
課表中會有兩個欄位,記錄老師的編號以及班級的編號。

class Curriculum < ActiveRecord
  belongs_to :teacher
  belongs_to :school_class
end

class Teacher < ActiveRecord
  has_many :school_classes, through :curriculums
end
 
class SchoolClass < ActiveRecord::Base
  has_many :teachers, through :curriculums
end

像這樣,設定的話,teacher跟schoolclass,就可以透過curriculum這個資料表存取到彼此,並互相擁有昨天說到的has_many方法:

teacher1 = Teacher.first
school_class1 = SchoolClass.first
# =====================#
teacher1.SchoolClasses #列出 teacher1 的所有 Schoolclass
SchoolClass1.teachers #列出 schoolclass1 的所有 teacher

(其他的就都不贅述啦,可以翻翻前一篇~)
若仔細觀察 console 裡的資訊,當寫下teacher1.SchoolClasses,其實是會去 curriculums 這個資料表裡面撈東西的!

至於has_many 後面有什麼方式可以做設定,請先參考官方文件

部落格實作

貼文分類系統

我們要從部落格的分類功能開始切入了,其實就是要先增加一個 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:

class PostsCategory < ApplicationRecord
  belongs_to :post
  belongs_to :category
end

目前資料表的關聯是:

接著去分別去 post 、 category 的 model

class Post < ActiveRecord
  has_many :category, through :post_categories
end
class Category < ActiveRecord
  has_many :posts, through :post_categories
end

此時的 model 關聯是:

這樣的話,在頁面中想要用分類來顯示出文章的話,只要使用:

categoy1 = Categoy.create(name:'ruby')

category1.posts

就可以囉~

感謝各位看到這邊,若有任何建議,請各位不吝指教!我們明天見!


上一篇
Day_13 model 一對多? & 部落格文章系統
下一篇
Day_15 devise?
系列文
Ruby on Rails 新手的30個問題!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言