1. Many-to-many relationships and the realization of multi-state students, courses, teachers
The relationship between the three is many-to-many, who shows the polymorphism of the class
Model Layer
Stu.rb
Has_many:summaries
Has_many:subjects,: Through =>:summaries,: Source =: Subject #实现多对多关系
Teacher.rb
Has_many:summaries,:as =:p eople,:d ependent =:d Estroy #实现多态
Has_many:subjects,: Through =>:summaries,: Source =: Subject #实现多对多关系
Subject.rb
Has_many:summaries
Has_many:teachers,: Through =>:summaries,: Source =:p Eople,: source_type = ' Teacher '
Has_many:stus,: through = Summaries,:source =:p eople,: source_type = ' Stu '
Summary.rb
Class Summary <activerecord::base
Belongs_to:p eople,:p olymorphic = True
Belongs_to:subject
End
Db/migrate Layer
Summary.rb
Create_table:summaries do |t|
t.integer:subject_id
T.string:p Eople_type
T.integer:p eople_id
End
Cases:
s = subject.new
t = teacher.new
S.teachers <<t
S.save
The data in the summary table is now updated
2, Name_scope (need to use the class name to call)
A) Named_scope:sub_stu,: conditions = "Shangke_type is null"
b) Named_scope:sub_stu,: conditions = "Shangke_type is null" do
def get_count
All.count:conditions = "id = 1"
End
End
This approach is equivalent to the way the DEF definition is performed on the contents of the conditions condition lookup. But in real execution, the DEF-defined method is converted into an SQL statement, executed with the condition statement.