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

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

  • 相关阅读:
    状态码
    vue+element下拉选项添加点击事件可跳转或触发事件
    position定位
    vue+element下拉菜单添加事件
    vue封装接口
    vue+element实现导入excel并拿到返回值
    10. EIGRP的stud
    9. EIGRP认证和默认路由
    8. EIGRP负载均衡
    7. EIGRP中应用偏移列表
  • 原文地址:https://www.cnblogs.com/zhangwending/p/3091745.html
Copyright © 2011-2022 走看看