has_many relation的几种类型

updated:
06/30/2013

0.1 image/video attach to news/article
[url=https://github.com/yankforce/polymorphic]project url[/url]

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


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自身关联,单向

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 有两种角色学生和老师,自身关联


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值