使用 HMTH 和多个连接模型的 Rails 查询
我正在使用 Rails 3,并希望根据下面的模型获取学生可以访问的课程,
class Student
has_many :students_levels
has_many :levels, :through => :students_levels
end
class Class
has_many :classes_levels
has_many :levels, :through => :classes_levels
end
class Level
has_many :students_levels
has_many :classes_levels
end
class StudentsLevel
belongs_to :students
belongs_to :levels
end
class ClassesLevel
belongs_to :classes
belongs_to :levels
end
我提出了下面的查询,但认为这似乎不是最好的 Rails 做事方式,并希望获得其他建议。谢谢,
Class.where(:id => (ClassesLevel.where(:level_id => Student.find(1).levels)))
我想将其作为实例方法添加到 Student 中,并且认为会有更好的方法来完成一些事情。
I am using Rails 3 and wanted to get the classes a student has access to based upon the model below
class Student
has_many :students_levels
has_many :levels, :through => :students_levels
end
class Class
has_many :classes_levels
has_many :levels, :through => :classes_levels
end
class Level
has_many :students_levels
has_many :classes_levels
end
class StudentsLevel
belongs_to :students
belongs_to :levels
end
class ClassesLevel
belongs_to :classes
belongs_to :levels
end
I came up with the query below but didn't think it seemed like the best Rails way to do things and wanted to get additional suggestions. Thx
Class.where(:id => (ClassesLevel.where(:level_id => Student.find(1).levels)))
I want to add this as an instance method to Student and was thinking there would be a better way doing something with has many through.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我完全不明白你的类结构背后的整个逻辑。为什么不将学生直接连接到班级?以及一个类如何可以有多个级别。我的意思是,如果你有 Math1 和 Math2,那么它们是不同的课程,对吧?或者你有数学1、2、3吗?
好吧,无论如何,如果您想使用当前的关联,这里是解决方案,我希望它适合您的需求:
抱歉,这仍然是 Rails 2.x 格式...
I quite did not understand the whole logic behind your class structure. Why you are not connecting students directly into a class? And how a class can have many levels. I mean if you have Math1 and Math2, those are different classes, right? Or do you have Math1,2,3?
Well, anyway, here's the solution if you want to use current assosiations, I hope it suites your needs:
And sorry, this is still in Rails 2.x format...