rails 多对多关系及多态

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的语句一起执行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值