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 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.

Answers


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...


Need Your Help

Should methods that implement pure virtual methods of an interface class be declared virtual as well?

c++ interface methods virtual

I read different opinions about this question. Let's say I have an interface class with a bunch of pure virtual methods. I implement those methods in a class that implements the interface and I do ...

package to switch on or off 3g and wifi on Android

android-wifi

Can anyone please tell me which SDK packages are used for switching on or off 3g and wifi on Android devices.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.