ruby-on-rails - 我如何消除一些查询?

标签 ruby-on-rails ruby ruby-on-rails-3

好的,我正在做这个

<% @courses.each do |course| %>
    <tr>
      <th>Users</th>
    </tr>
  <tr>
    <td>
     <span><%= course.not_competent %></span> <span><%= course.novice %></span></td>
  </tr>
<% end %>

在我的类(class)模型中我有这个

def novice
  self.courses_users.low_scores.collect{|score| score.user.username}.join(', ')
end

def not_competent
  self.courses_users.really_low_scores.collect{|score| score.user.username}.join(', ')
end

问题是这种方法会运行数以千计的查询....有没有更好的方法不会降低数据库

最佳答案

对@Zabba,首先尝试更改填充@courses 的调用并添加类似于此参数的内容

:include => [{:courses_users => :low_scores}]

或链

.includes([{:courses_users => :low_scores}])

(我想 low_scores 是你模型的另一个关联)

以这种方式,Activerecord 更改了包含嵌套表的第一个查询。在此 ascii_cast一些例子。

希望对你有用

关于ruby-on-rails - 我如何消除一些查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938908/

相关文章:

ruby-on-rails - Rails 嵌套属性创建,但不更新,不删除

ruby-on-rails - rails/Postgres : Error after changing pg gem version

ruby-on-rails - 根据条件重构 Rails ActiveRecord

ruby - 基因图算法

ruby-on-rails - 我可以在 :all with capybara? 之前使用吗

ruby-on-rails - 何时使用设计与创建我自己的身份验证

ruby-on-rails - ActiveRecord : Attributes protected by default. 它们如何公开?

ruby-on-rails - rails "secret_token"对 config.session_store( :cache_store)?) 仍然很重要

javascript - sinatra javascript 调用

ruby-on-rails - 从设计 "User does not respond to ' 设计方法中获取错误“运行 "rails generate devise:install"时