zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    TypeScript-基础-09-声明文件
    TypeScript-基础-08-类型断言
    TypeScript-基础-07-函数的类型
    TypeScript-基础-06-数组的类型
    TypeScript-基础-05-对象的类型—接口
    TypeScript-基础-04-联合类型
    TypeScript-工程
    小白学前端03
    小白学前端02
    小白学前端
  • 原文地址:https://www.cnblogs.com/zhangwending/p/3091745.html
Copyright © 2011-2022 走看看