# [08/09_d] 關聯性 目前2個Model User 有4個欄位 > :id :email : pw :account Note 有4個欄位 > :id :title :content :deleted_at ## 資料類型 * **:belongs_to** 資料類型,會長出id,還會在新的model中長出belongs_to 只加 belongs_to, 要自己加 has_many、has_one * **:index** 資料類型 會在 Rails 內增加 add_index,並且指定 INT 型態 ## 所謂關聯 has_one 一對一 has_many 一對多 多對多 一個User會有很筆記 Note,是一對多 因此Note屬於/belongs_to 某User * 其中被User一對多的欄位=**user_id**(本Note屬於哪位User),將當於FK * 而User本體的id是PK ### has many 此類別方法,不是建立關聯,建立關聯是 add_reference has_many 會幫你建立 4 個方法! * has_many :notes * .notes * 抓到目標user * .notes= 對應belongs_to :user 不一定兩邊都要寫,看你有沒有需要用到那個方法 ## 建立migration 長出FK 為了將FK加回USER,要新增一個migration(add_user_to_note) > $rails **g migration** add_user_to_note 記得rails db:migrate 在db/migrate裡面的新檔(2021時間戳記_add_user_to_note.rb)寫 > **add_column** :notes, :user_id, :integer * 若非 add_column 改為 **add_refernce(:表格名稱, :欄位名稱, 可以指定FK)** ,產生 user_id以外還會加索引 * 會在notes表單長出一個user_id欄位(依第二欄的名稱) > > add_refernce(:notes, :user, :foreign_key: true) * 檢查schema,會發現多了user_id欄位 * 若在SQLite的browse data界面將user_id改成4,再到rails s 撈 Note.where(user_id: 4),扣掉假刪除的,會一樣多筆 ## 因此可運用方法has_many/belongs_to 在Model裡(user.db)加上類別方法 has_many :notes 的話,會加4個方法(notes、notes = 、notes.new、notes.create)上會精確找出篩選的筆數。在rails c裡面尋找u4.notes造成4個結果。 ![](https://i.imgur.com/8TxRvnU.png) 與has_many相對,通常也會在notes.rb寫上belongs_to: User。 沒有要運用方法的話(如:用n3.user抓出寫3號筆記的人),可不寫。 ###### tags: `Rails`