首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 4急切加载(关联与方法)的效率

Rails 4急切加载(关联与方法)的效率
EN

Stack Overflow用户
提问于 2015-01-27 01:38:04
回答 1查看 252关注 0票数 0

下面的方法和关联完成了同样的事情。它们都为当前学校提供了一种“active_students”方法。但是,关联使用125个查询,该方法使用1。该方法使用预加载,但是,关联似乎更像是rails的方式。

为什么与建立帐户外查询相比,school.accounts的效率如此之低?是否有可能保持关联并在其上使用急切加载?我的方法方法合适吗,或者有更好的方法来解决这个问题?

代码语言:javascript
复制
  # 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)
  end

vs

代码语言:javascript
复制
  # 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
EN

回答 1

Stack Overflow用户

发布于 2015-01-28 14:03:02

@hellion,我认为这些博客

而可以帮助你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28155550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档