---
title: "has_many relation的几种类型"
author: "夜鸣猪"
date: "2012-06-25T20:43:28Z"
tags: []
categories: ["编程语言"]
slug: "has-many-relation"
draft: false
lastmod: "2013-07-01T04:47:44Z"
id: 1567722
url: "https://hlee.iteye.com/blog/1567722"
---

updated:
06/30/2013

0.1 image/video attach to news/article
[project url](https://github.com/yankforce/polymorphic)

```ruby

class Article < ActiveRecord::Base
  has_many :attachable_entities, as: :entity
  has_many :attachables, through: :attachable_entities, source: :attachable, source_type: Image 
end

class AttachableEntity < ActiveRecord::Base
  belongs_to :entity, polymorphic: true
  belongs_to :attachable, polymorphic: true
end

class Image < ActiveRecord::Base
  has_many :attachable_entities, as: :attachable
  has_many :entities, through: :attachable_entities, source: :entity, source_type: Article 
end

```




1 老师学生 many to many


```ruby

class Student < ActiveRecord::Base
  attr_accessible :name
  has_many :student_teacher_links
  has_many :teachers, through: :student_teacher_links
end

class Teacher < ActiveRecord::Base
  attr_accessible :name
  has_many :student_teacher_links
  has_many :students, through: :student_teacher_links
end

class StudentTeacherLink < ActiveRecord::Base
  belongs_to :student
  belongs_to :teacher
  # attr_accessible :title, :body
end


```


2. User friends自身关联，单向

```ruby

class User < ActiveRecord::Base
  attr_accessible :name

 has_many :friend_links 
 has_many :friends, through: :friend_links

 has_many :ofriend_links, foreign_key: :friend_id, class_name: :FriendLink
 has_many :ofriends, through: :ofriend_links,  source: :user

 def allfriends
   friends + ofriends
 end
end


class FriendLink < ActiveRecord::Base
  attr_accessible :friend_id, :user_id

  belongs_to :user
  belongs_to :friend, class_name: :User
end


```


3. User 有两种角色学生和老师，自身关联


```ruby

class User < ActiveRecord::Base
  attr_accessible :name

  has_many :student_links, foreign_key: :student_id, class_name: :StudentTeacherLink
  has_many :students, through: :student_links
  has_many :teacher_links, foreign_key: :teacher_id, class_name: :StudentTeacherLink
  has_many :teachers, through: :teacher_links


  #has_many :students, through: :student_teacher_links#, source: :student_id#, class_name: :StudentTeacherLink
  #has_many :teachers, through: :student_teacher_links#, class_name: :StudentTeacherLink
end

class StudentTeacherLink < ActiveRecord::Base
  attr_accessible :student_id, :teacher_id
  belongs_to :teacher, foreign_key: :student_id, class_name: :User#as: :student_id
  belongs_to :student, foreign_key: :teacher_id, class_name: :User#as: :student_id
  #belongs_to :user#, as: :teachers
end


```