亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

建立兩個模型之間多對多的關聯關系

標簽:
Ruby

有两种方式 has_many :through 和 has_and_belongs_to_many

第一种:has_many :through

Class Assembly < ApplicationRecord
    has_many :manifests                                                                                                             
    has_many :parts, through:manifestsendClass Manifest < ApplicationRecord
    belongs_to :assembly
    belongs_to :partendClass Part < ApplicationRecord
    has_many :manifests
    has_many :assemblies, through: :manifestsend

相应迁移如下:

class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
  def change
    create_table :assemblies do |t|
      t.string :name
      t.timestamps    end
 
    create_table :parts do |t|
      t.string :part_number
      t.timestamps    end
 
    create_table :assemblies_parts, id: false do |t|
      t.belongs_to :assembly, index: true
      t.belongs_to :part, index: true
      t.timestamps    end
  endend

第二种:has_and_belongs_to_many

比较简单,可以直接建立关联,不需要关联模型,但是同样需要创建关联表

Class Assembly < ApplicationRecord
    has_and_belongs_to_many :partsendClass Part < ApplicationRecord
    has_and_belongs_to_many :assembliesend

相应迁移如下:

class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
  def change
    create_table :assemblies do |t|
      t.string :name
      t.timestamps    end
 
    create_table :parts do |t|
      t.string :part_number
      t.timestamps    end
 
    create_table :assemblies_parts, id: false do |t|
      t.belongs_to :assembly, index: true
      t.belongs_to :part, index: true
    end
  endend

对比

  1. 如果想把关联模型当做实体使用,要用has_many :through关联,

  2. 如果不需要使用关联模型,建立has_and_belongs_to_many关联更简单(不过要记得在数据库中创建联结表)

  3. 如果要对联结模型做数据验证、调用回调,或者使用其他属性,要使用 has_many :through 关联。



作者:小新是个程序媛
链接:https://www.jianshu.com/p/68f8cc293b2f

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消