【问题标题】:Call a query (controller action) inside views在视图中调用查询(控制器操作)
【发布时间】:2017-05-31 06:48:28
【问题描述】:

我正在尝试创建一个表格,该表格主要按日期显示每个字段的数字。这个我只有一个模型

查看:

<table class="table-table-verif">
      <thead class="fixed_headers">
      <tr id = "thead-title">
        <th>Date</th>
        <th># True Positive</th>
        <th># True Negative</th>
        <th># False Positive</th>
        <th># False Negative</th>
      </tr>
      </thead>

      <tbody>
       <% @verification.each do |s| %>
        <tr id="thead-value">
          // what to do here?
        </tr>
       <% end %>
      </tbody>
    </table>

我想在我的控制器中调用这些查询。

控制器:

  def date
    @verification = Verification.group(:Date).where("Findings = ? or Findings = ?", 'False Positive','False Negative').order(Date: :asc).count
  end

  def number_true_positive
    Verification.group(Date).where("Findings = ?", 'True Positive').order(Date: :asc).count
  end

  def number_false_positive
    Verification.group(:Date).where("Findings = ?", 'False Positive').order(Date: :asc).count
  end

  def number_true_negative
    Verification.group(:Date).where("Findings = ?", 'True Negative').order(Date: :asc).count
  end

  def number_false_negative
    Verification.group(:Date).where("Findings = ?", 'False Negative').order(Date: :asc).count
  end

每一列都要统计各自记录的数量,并根据它们的日期将数字放在各自的&lt;th&gt;上。

有什么更好的方法?

【问题讨论】:

  • 将这些查询写入helper 方法。
  • Controller 是放置那些 methods 的好地方。您应该将它们移至 model
  • 如果你只需要计数,为什么还要ordering呢?
  • @Md.FarhanMemon 因为我使用的是 .group,我想根据日期和升序显示结果。
  • @Emu 我将如何实现这个?我的意思是如何调用辅助方法来查看视图?

标签: html mysql ruby-on-rails ruby controller


【解决方案1】:

我看到你的代码中有很多重复,你可以为每个子查询创建scopes,并且可以有多个组合。

在你的verification.rb

scope :date_grouped, -> { group(:Date) }

scope :falsy, -> { where("Findings = ? or Findings = ?", 'False Positive','False Negative') }

scope :truthy, -> { where("Findings = ? or Findings = ?", 'True Positive','True Negative') }

scope :findings_by, -> (value) { where(Findings: value) }

scope :date_asc, -> { order(Date: :asc) }

现在您可以根据需要调用它们。

例如

<%= Verification.date_grouped.falsy.date_asc %>
<%= Verification.date_grouped.truthy.date_asc %>
<%= Verification.date_grouped.findings_by('True Positive').date_asc %>

【讨论】:

  • 我还不熟悉范围,将阅读它的文档。感谢您的建议,将尝试这个:)
  • 我已经设置了所有必要的范围,我将如何在我的视图上实现它(调用它们)?
  • 例如部分是您必须进行的调用才能获得结果,检查更新
  • 谢谢!我现在有点让它工作了,但目前,它只显示在一行中,我认为查询是在调用查询的列上调用的。我该怎么做,首先列出所有日期,然后计算每个日期记录的存在?无论如何,非常感谢你帮助我:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多