【问题标题】:How to retrieve selective objects from a database ? Objetcs rendered redundantly如何从数据库中检索选定的对象?冗余渲染的对象
【发布时间】:2015-07-09 14:37:10
【问题描述】:

我试图在我的数据库中检索一些对象,但我不知道如何。 我尝试了范围但没有成功,但我认为这不是正确的解决方案。

这是我主要涉及的文件(删除了不必要的行):

# app/controllers/operators_controller.rb
class OperatorsController < ApplicationController
  def index
    @operators = Operator.all.sort_by_newest
  end

具有以下范围:

# app/models/operator.rb
  scope :sort_by_newest, -> { order('created_at DESC') }

然后

# app/views/operators/index.html.erb
<ul class="operators">
  <%= render @operators %>
</ul>

调用以下部分:

# app/views/operators/_operator.html.erb
<% @operators.where(local:true).find_each do |operator| %>
  <li><%= link_to operator.name, operator %></li>
<% end %>

运算符有一个Local 值(布尔值,默认为false),有3 个元素,其中local = true(然后是36,其中local = false)。

2.2.0 :003 > Operator.all.count
   (0.2ms)  SELECT COUNT(*) FROM "operators"
 => 39
2.2.0 :004 > Operator.where(local: true).count
   (0.4ms)  SELECT COUNT(*) FROM "operators" WHERE "operators"."local" = 't'
 => 3
2.2.0 :005 > Operator.where(local: false).count
   (0.2ms)  SELECT COUNT(*) FROM "operators" WHERE "operators"."local" = 'f'
 => 36

问题是:它为我渲染了 3 个 local=true 元素... 39 次!

我需要的 3 个单个对象是橙色的。渲染了 39 次。

如何做到这一点?

编辑:

我想在很多页面中有很多渲染(一个带有“local:true”元素,另一个带有“global:true”元素等)所以我想我不能直接修改为操作符:索引方法?

【问题讨论】:

  • 试着把这个@operators = Operator.all.sort_by_newest改成@operators = Operator.where(local: true).sort_by_newest
  • 执行此操作时,它会为我呈现 9 个结果:我需要的 3 个对象的 3 倍(就像@MurifoX 的答案一样)。
  • 我需要补充一点:我想在许多页面中进行许多渲染(一个带有“local:true”元素,另一个带有“global:true”元素等)

标签: ruby-on-rails database activerecord sqlite


【解决方案1】:

您正在做重复的工作。尝试使用特定查询在控制器操作中搜索运算符:

def index
  @operators = Operator.where(local: true).sort_by_newest
end

然后只打印 operator 属性,而不在您的部分中使用迭代器:

<li><%= link_to operator.name, operator %></li>

【讨论】:

  • 您好 Murifo,感谢您的回答。我刚刚尝试过:现在它为我呈现 9 个结果,是我需要的 3 个对象的 3 倍......
  • 嗯,这与 Rails 如何在内部处理部分有关。 (guides.rubyonrails.org/…) 你不需要遍历operators。删除迭代器,我相信它会没事的。
【解决方案2】:

当您调用&lt;%= render @operators %&gt; 时,它将呈现_operator.html.erb 部分。但是您不需要遍历 @operators 对象来渲染每个单独的 @operators 对象。假设您在 each 块中,只需编写代码:

<li><%= link_to operator.name, operator %></li>

【讨论】:

    【解决方案3】:

    对于我在编辑 OP 后提出的问题(如何在不触及 operator:index 方法的情况下提出请求)自行评论

    您可以在不接触 operator:index 方法的情况下拥有数据库的多个视图:

    # app/model/operator.rb
    def index
      @operators = Operator.all.sort_by_newest
    end
    

    以及接受请求的渲染(如前所述,实际上是迭代的,所以不需要迭代到部分,否则你会有重复):

    <%= render @operators #%>
    <%= render @operators.where(local:true) %>
    <%= render @operators.where(global:true) %>
    

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多