首页 > 解决方案 > 如何在重定向到 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>

标签: ruby-on-railsrubyhaml

解决方案


您的问题来自方法本身的定义。您已经声明了您的方法total_matchesanalysis_result.rb但您正在调用analysis.results.total_matches. 我会写analysis.total_matches

奖金:

我建议在您的方法之上添加一个保护条款total_matches

def total_matches
  return 0 unless self.patterns
  # ...
end

推荐阅读