Rails query using HMTH and multiple join models
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开发者_StackOverflow社区 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.
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:
Class Student
...
def available_classes
Class.find(:all,
:include => {:levels => {:students_levels => :student}},
:conditions => ["students.id = ?", self.id])
end
And sorry, this is still in Rails 2.x format...
精彩评论