updated:
06/30/2013
0.1 image/video attach to news/article
[url=https://github.com/yankforce/polymorphic]project url[/url]
1 老师学生 many to many
2. User friends自身关联,单向
3. User 有两种角色学生和老师,自身关联
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