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

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

posted @ 2013-05-21 22:15  ZeRolin  阅读(598)  评论(0编辑  收藏  举报