【问题标题】:Where function equivalent for eager loading in rails与 Rails 中的急切加载等效的功能
【发布时间】:2013-02-06 17:16:18
【问题描述】:

我正在尝试通过预先加载来优化我的代码,但是无论何时调用函数,都会在日志中执行查询。

@votes_list = Vote.joins(:user => :profile).where(:post_id => post.id)
@male_votes = @votes_list.where(:profiles => { :gender => 1 }).count
@female_votes = @votes_list.where(:profiles => { :gender => 2 }).count

我试图在第一个查询之后进行一些查询,而不需要从数据库中获取,该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby database ruby-on-rails-3 rails-activerecord


    【解决方案1】:

    您希望为每次投票急切地加载用户及其个人资料。然后,您可以在个人资料中选择按性别划分的内存投票子集。

    @votes_list = Vote.where(:post_id => post.id, :include => { :user => :profile })
    @male_votes = @votes_list.select {|v| v.user.profile.gender == 1}
    @female_votes = @votes_list.select {|v| v.user.profile.gender == 2}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多