新手问题 关于多对多条件查询

hicupp · July 01, 2013 · Last by reyesyang replied at July 02, 2013 · 2784 hits

大家好: 问题描述:有两个 model,Student 和 Teacher,它们是多对多的关系。中间的关系模型为 Student_Teahcer. 在 student_teachers 表里有 4 个字段:id,student_id, teacher_id 以及 mark。mark 字段有两种状态:0 和 1. 当我想调用 @students = teacher1.students

时,怎么才能实现调用结果里 students 和 teacher1 在 student_teacher 对应的 mark 字段为 1.能通过申明 has_many 关系时用 where 或者 condition 么?还是其他方法?

直接在 where 中写条件,如果会多次使用的话,可以考虑添加 scope teacher1.students.where('student_teachers.mark = 0')

可以哈。最后我的解决方案是在申明多对多关系时加了条件: :conditions => {:mark => '0'}

#2 楼 @hicupp 如果程序里没有需要查询另一个状态的需求的话,确实这样会更加简洁

You need to Sign in before reply, if you don't have an account, please Sign up first.