關聯有:一對一、一對多、多對多
一對一,最簡單
比如一個男生擁有一個女朋友,注意都是單數
# app/models/boy.rb class Boy < ActiveRecord::Base has_one :girlfriend end # app/models/girlfriend.rb class Girlfriend < ActiveRecord::Base belongs_to :boy end
一對多,假設一個男生有很多女朋友(舉例而已不要激動),要注意到has_many後面接的是複數,因為是一對多
# app/models/boy.rb class Boy < ActiveRecord::Base has_many :girlfriends end # app/models/girlfriend.rb class Girlfriend < ActiveRecord::Base belongs_to :boy end
多對多的觀念比較複雜
舉例來說有一個男生班和一個女生班,於是我們有兩個 table 各自記錄男女生的資料
男生班的男生,和女生班的女生約會,約會記錄就要記在另一個date table
因為一個男生可能和很多女生約會,一個女生也可能和很多男生約會,總之一次約會一筆記錄,如下(同樣請注意單複數)
# app/models/boy.rb class Boy < ActiveRecord::Base has_many :dates has_many :girls, through: :dates end # app/models/girl.rb class Girl < ActiveRecord::Base has_many :dates has_many :boys, through: :dates end # app/models/date.rb class Date < ActiveRecord::Base belongs_to :boy belongs_to :girl end
date table至少有三個欄位,id, boy_id, girl_id;它自己的id做為約會序號,以及記錄該次約會是哪個男生女生的boy_id, girl_id
這個date table就是join table
還有一個多對多的設定方法 has_and_belongs_to_many
# app/models/boy.rb class Boy < ActiveRecord::Base has_and_belongs_to_many :girls end # app/models/girl.rb class Girl < ActiveRecord::Base has_and_belongs_to_many :boys end
這在實務上很少用,因為你不能去設join tbale的欄位,略知即可
沒有留言:
張貼留言