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

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

  • 相关阅读:
    dojo自定义Widget
    奇怪的JS
    Dojo Widget系统(转)
    JS 中Promise 模式
    Structs 原理图
    ArcGIS Engine Style文件操作
    dojo.hitch 原理
    Android:解决cannot find zipalign的问题
    Bootstrap:解决Bootstrap下拉框需要双击才能打开的问题
    Clojure:添加gzip功能
  • 原文地址:https://www.cnblogs.com/zhangwending/p/3091745.html
Copyright © 2011-2022 走看看