Ruby on rails開發從頭來(五十七)- ActiveRecord基礎(多對多關聯關係)

來源:互聯網
上載者:User

在Rails中多對多關聯通過在關聯表對應的類中聲明has_and_belongs_to_many來實現。

在資料庫中,多對多關聯使用中間表來實現,表中包括關聯表的主鍵,Active Record假定這個中間表的名字是由關聯表的名字根據字母的順序串聯起來得到的。例如,關聯表為categories和products,中間表的名字就是categories_products。

注意我們的關聯表沒有id列,有兩個原因,首先,不需要一個唯一的標識來識別兩個外鍵之間的串連,我們定義表的語句像下面這樣:

create table categories_products (category_id int not null,product_id int not null,constraint fk_cp_category foreign key (category_id) references categories(id),constraint fk_cp_product foreign key (product_id) references products(id),primary key (category_id, product_id));

第二個原因在中間表中不包括一個id列,Active Record在訪問某個行時會自動包含所有的列。如果包含了一個id列,那麼這個id列就會複寫掉在關聯表中的id列。

The has_and_belongs_to_many() 聲明

has_and_belongs_to_many在很多方面很像has_many,has_and_belongs_to_many建立了本質上是一個集合的屬性,該屬性支援和has_many相同的方法。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.