2008-04-25

宝典:第八式 表间关联NORMAL

关键字: 表间关联 
首先我们继续在easy里面提到的一对多的 Questions-Answers
这里已经有了题目了,有题目了接下来要干什么咧,  做题目
这里我们就加入Users 与 notes
notes记录谁做过那个题,选择的答案
关系就这样理解
这个图片怎么传上去啊???


然后是加入关联代码

几个模型中分别为
class Answer < ActiveRecord::Base
    belongs_to :question    
    has_many :users , :through => :notes 
    has_many :notes , :dependent =>  :destroy 
    end

class Question < ActiveRecord::Base
  has_many :answers ,:dependent =>  :destroy
  has_many :notes
  has_many :users , :through => :notes 
end  

class User < ActiveRecord::Base
 has_many :notes
  has_many :questions , :through => :notes
  has_many :answers , :through => :notes 
end

class Note< ActiveRecord::Base
  belongs_to :question
  belongs_to :answer
  belongs_to :user
end



上面完成的都是等同与配制比较枯燥,下面的将是神奇的了,用"敏捷之道"的话说,就是魔法即将来临.
##只需要取出相应的字段后下面即可实现
@user.questions         ##这个人做过的所有题目(纪录集)
@user.answers      ##这个用户选择过的所有答案(纪录集)
@user.notes       ##这个用户的所有做题纪录(纪录集)
@question.users     ##做过这个题目的所有人(纪录集)
@answer.users      ##选择过这个答案的所有人(纪录集)


不知道表达得怎么样,有什么不懂欢迎留言提问,或者去http://sayid2008.javaeye.com/blog/157405看看
评论
发表评论

您还没有登录,请登录后发表评论

sayid2008
搜索本博客
最近加入圈子
存档
最新评论