ruby-on-rails - 如何在重定向到 Rails 中的链接之前使用“if”语句
问题描述
我在一个名为的模型中定义了这个analysis_result.rb
:
def total_matches
return 0 unless self.patterns
self.patterns.sum do |_, v|
matches = v.matches.try(:count) || 0
if v.additional.present? && v.additional['ggroup'].present?
bc_matches = v.additional['ggroup'].try(:count) || 0
else
bc_matches = 0
end
matches + bc_matches
end
end
我试图在一个名为的视图中使用它,_rable_row.haml
以便事先检查是否 total_matches
为 0。如果它是 0 我想显示部分而不是让用户转到链接。
这是视图中要检查的代码if analysis.results.total_matches != 0
:
%tr.form-table__row{ class: ('form-table__row--disabled' if analysis.processing?) }
%td.form-table__data= check_box_tag "checkbox_object_ids[]", analysis.id
%td.form-table__data
- if analysis.results.total_matches == 0
= render partial: 'partials/shared/empty'
- elsif analysis.results.total_matches != 0
= link_to analysis.title, analysis, class: 'js-toggle', data: { href: "loading-#{analysis.id}" }
- unless analysis.viewed
%span.dashboard__icon.dashboard__icon--small.fa.fa-circle.text-info{ aria: { hidden: 'true' }, title: 'New' }
我明白了undefined method 'total_matches' for #<Mongoid::Criteria:0x00007fc51c5e3720>
解决方案
您的问题来自方法本身的定义。您已经声明了您的方法total_matches
,analysis_result.rb
但您正在调用analysis.results.total_matches
. 我会写analysis.total_matches
。
奖金:
我建议在您的方法之上添加一个保护条款total_matches
def total_matches
return 0 unless self.patterns
# ...
end
推荐阅读
- amazon-web-services - AWS 目标组在同一个 ECS 任务上注册 2 个目标?
- php - PHP CURL:随机非常慢
- python - Python:保存变量名并稍后在循环中使用它们
- c++ - 在 C/C++ 中调用函数未定义行为时是否省略返回?
- postscript - 两页上的后记模糊了第一页
- azure-web-app-service - 如何以编程方式检查 Azure 应用服务计划是否支持 P1V3 层
- java - 不返回整个大的 json 响应
- c++ - 在文件 .asm 中使用全局变量
- html - 为每个 boostrap 轮播项目添加背景 img
- azure-cognitive-search - 如何从 Synapse Spark 写入 Azure 搜索索引?