使用 HMTH 和多个连接模型的 Rails 查询

发布于 2024-10-05 18:44:14 字数 744 浏览 5 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

负佳期 2024-10-12 18:44:14

我完全不明白你的类结构背后的整个逻辑。为什么不将学生直接连接到班级?以及一个类如何可以有多个级别。我的意思是,如果你有 Math1 和 Math2,那么它们是不同的课程,对吧?或者你有数学1、2、3吗?

好吧,无论如何,如果您想使用当前的关联,这里是解决方案,我希望它适合您的需求:

 Class Student      
 ...
 def available_classes
    Class.find(:all, 
      :include => {:levels => {:students_levels => :student}}, 
      :conditions => ["students.id = ?", self.id])
  end

抱歉,这仍然是 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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文