在我的Rails应用程序中,我使用Rubocop来判断问题.今天它给了我一个这样的错误:Assignment Branch Condition size for show is too high.这是我的代码:

def show
  @category = Category.friendly.find(params[:id])
  @categories = Category.all
  @search = @category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
  rate
end

这意味着什么?我如何修复它?

推荐答案

分配分支条件(ABC)大小是对方法大小的度量.它基本上是通过计算A个选区、B个牧场和C个条件语句的数量来确定的.(more detail..)

为了降低ABC分数,你可以将其中一些作业(job)转移到"行动前要求"中:

before_action :fetch_current_category, only: [:show,:edit,:update] 
before_action :fetch_categories, only: [:show,:edit,:update] 
before_action :fetch_search_results, only: [:show,:edit,:update] #or whatever

def show
  rate
end

private

def fetch_current_category
  @category = Category.friendly.find(params[:id])
end

def fetch_categories
  @categories = Category.all
end

def fetch_search_results
  @search = category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
end

Ruby-on-rails相关问答推荐

如何在_serialize之前执行代码?""或者如何在序列化属性之前对属性进行清理?

Gemfile需要较新版本的依赖项

方法和括号之间没有空格时出错

用变量替换 find_or_create_by 中的键

Rails 使用多个外键创建/构建

为什么是 json.partial!使用新的哈希语法传递本地时,jbuiler 模板中的行不执行?

如何让删除链接响应 Rails 7 中的 turbo_stream 和 html?

Ruby on Rails form_with 不显示错误,卡在服务器端

ActiveRecord 包括.指定包含的列

Rails 模型.有效吗?刷新自定义错误并错误地返回 true

Rails 3 - Select 包含?

如何在 YAML 中声明带有单引号和双引号的字符串?

Rails 3 中图像路径的完整 url

Rails 3:如何正确显示textarea中的文本?

如何在我的 Gemfile 中找到未使用的Ruby

Rails Active Admin css 与 Twitter Bootstrap css 冲突

关于在不适合任何地方的 Rails 应用程序中放置类的指南

如何拯救 OmniAuth::Strategies::OAuth2::CallbackError?

错误:无法构建 gem 原生扩展 - 安装 mysql2 时出错

Ruby 1.87 与 1.92 Date.parse