【问题标题】:How to dry given query code in rails如何在rails中干燥给定的查询代码
【发布时间】:2015-07-14 07:26:28
【问题描述】:

我已经给出了这个代码

@classes  = Class.includes(:student_classes).where(:employee_id => current_employee.id)
  @students = {}

    unless @classes.blank?
      @classes.each { |class|
        unless class.student_classes.blank?
          class.student_classes.each { |std|
            @students[std.student.id] = std.student.name
          }
        end
      }
    end

获取@students。请指导我如何干燥这个查询。提前致谢。

【问题讨论】:

  • 我想你的类是用has_many :student_classes 声明的。只需添加has_many :students, through: :student_classes 并致电Class.where(employee_id: current_employee.id).students。如需更多信息,您可以(并且应该)阅读这篇文章guides.rubyonrails.org/…
  • 是的,我只有这个关联

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

最好的方法:

Student
  .joins(student_classes: [:class])
  .where(classes: {employee_id: current_employee.id})

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    相关资源
    最近更新 更多