下面的方法和关联完成了同样的事情。它们都为当前学校提供了一种“active_students”方法。但是,关联使用125个查询,该方法使用1。该方法使用预加载,但是,关联似乎更像是rails的方式。
为什么与建立帐户外查询相比,school.accounts的效率如此之低?是否有可能保持关联并在其上使用急切加载?我的方法方法合适吗,或者有更好的方法来解决这个问题?
# application_controller
def active_students # 1 query
# used by simply calling active_students
Account.includes(:role, {user: :school}).where(status: 0).where("roles.name = ?", 'student').where("users.school_id = ?", current_school.id).references(:role, :user, :school)
endvs
# school.rb
# used by calling current_school.active_students
# 125 queries
has_many :active_students, -> { joins(:role).where( "roles.name = ? AND accounts.status = ?", "student", 0 ) }, source: :accounts, through: :users发布于 2015-01-28 14:03:02
@hellion,我认为这些博客
而可以帮助你。
https://stackoverflow.com/questions/28155550
复制相似问题