我正在尝试创建一个表格,主要按日期显示每个相应字段的数字。我只有一个型号
查看:
<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>
我想在我的 Controller 中调用这些查询。
Controller :
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
每一列都应该统计各自的记录数,并将数字放在各自的<th>
上根据他们的日期。
更好的方法是什么?
最佳答案
我发现您的代码中有很多重复,您可以创建 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 %>
关于html - 在 View 内调用查询( Controller 操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44277564/