栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Ruby开发

建立两个模型之间多对多的关联关系

Ruby开发 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

建立两个模型之间多对多的关联关系

有两种方式 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

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/226369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号