• Ruby on Rails 模型关联(多对多关系)


    很基础,但是却搞很久,在这里总结一下。

    class User < ActiveRecord::Base
      has_many :borrows
      has_many :books, :through => :borrows
    end
    class Book < ActiveRecord::Base
      has_many :borrows
      has_many :users, :through => :borrows
    end
    class Borrow < ActiveRecord::Base
      belongs_to :user
      belongs_to :book
    end

    非常基础的多对多关系模型,需要注意的是申明的时候,不但要申明 has_many 另一个模型,同样要申明 has_many 创建的关系表,这里User和Book是一个多对多关系,他们的关系为Borrow。之后,

    @user.books
    @book.users

    就能查询出某个用户借阅了哪些书,某本书被哪些用户借阅了。

    引申一下,多表关联,

    class Grade < ActiveRecord::Base
        has_many :classrooms
        has_many :students, :through => :classrooms
    end
    class Classroom < ActiveRecord::Base
        belongs_to :Grade
        has_many :students
    end
    class Student < ActiveRecord::Base
        belongs_to :Classroom
    end

    年级类Grade有多个班级Classroom,班级有多个学生Student,通过 has_many, :through 的方式,就能查询到这个年级下的所有学生。

    @grade.students

    可以再引申出,一对一对一的关系模型。

  • 相关阅读:
    5种排序算法
    Numpy 基础
    Git 帮助
    SpringBoot巧用 @Async 提升API接口并发能力
    延时队列实现的方式总结
    Spring Boot 进行优雅的字段校验
    分布式搜索引擎Elasticsearch的架构分析
    Redis 使用规范
    Intellij IDEA远程debug线上项目记录
    领域驱动设计:领域接口化设计
  • 原文地址:https://www.cnblogs.com/zhangwending/p/3091745.html
Copyright © 2020-2023  润新知