1、多对多关系并实现多态 学生、课程、老师
三者之间彼此为多对多的关系,谁上课体现了多态的性
model层
stu.rb
has_many :summaries
has_many :subjects, :through =>:summaries, :source => :subject #实现多对多关系
teacher.rb
has_many :summaries,:as => :people,:dependent => :destroy #实现多态
has_many :subjects, :through =>:summaries, :source => :subject #实现多对多关系
subject.rb
has_many :summaries
has_many :teachers, :through =>:summaries, :source => :people, :source_type => 'Teacher'
has_many :stus, :through => :summaries,:source => :people, :source_type => 'Stu'
summary.rb
class Summary <ActiveRecord::Base
belongs_to :people, :polymorphic => true
belongs_to :subject
end
db/migrate层
summary.rb
create_table :summaries do |t|
t.integer :subject_id
t.string :people_type
t.integer :people_id
end
例:
s = Subject.new
t = Teacher.new
s.teachers <<t
s.save
此时summary表中的数据会被更新
2、name_scope(需要用类名来调用)
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
此种方式相当于对conditions的条件查找出的内容执行def定义的方法。但是在真正执行的时候,def定义的方法会被转化为SQL语句,和condition的语句一起执行。