【发布时间】:2019-10-26 04:58:19
【问题描述】:
我正在处理一项奖学金申请,人们可以通过捐款来支持他们想要参与的不同计划。我需要一些帮助来帮助我在 Rails 中进行 Rubocop 重构。
我有以下问题;
- 控制器动作只调用一个模型方法而不是初始 找到或新的。在模型中创建自定义 .new 或 .update 方法 所有必要的。
- 索引的分配分支条件大小太大 高
- 方法行数过多
我已经尝试重构代码,但我仍然面临与代码相同的问题。
我的代码是;
仪表板控制器(初始*)
class DashboardController < ApplicationController
def index
#Paid Donations in Chart
@paid_donations = Donation.where(payment: true).count
#Unpaid Donations in Chart
@unpaid_donations = Donation.where(payment: false).count
#Total Donations Sum
@total_donations_sum = Donation.where(payment: true).sum(:amount)
#Deployed Donations
@deployed_donations = Donation.where(deployment: true).sum(:amount)
#Not Deployed Donations
@not_deployed_donations = Donation.where(deployment: false, payment: true).sum(:amount)
#Deployed Donations Percentage
@deployed_donations_percentage = (@deployed_donations.to_f / @total_donations_sum.to_f) * 100
#Not Deployed Donations Percentage
@not_deployed_donations_percentage = (@not_deployed_donations.to_f / @total_donations_sum.to_f) * 100
#Total Donations
@total_donations = Donation.count
#Paid Donations
@paid_donations = Donation.where(payment: true).count
#Unpaid Donations
@unpaid_donations = Donation.where(payment: false).count
#All Programs
@programs = Program.all
end
end
仪表板控制器(重构)
class DashboardController < ApplicationController
def index
# Paid Donations in Chart
@paid_donations = Donation.paid_count
# Unpaid Donations in Chart
@unpaid_donations = Donation.unpaid_count
# Total Donations Sum
@total_donations_sum = Donation.paid_sum
# Deployed Donations
@deployed_donations = Donation.deployed_sum
# Not Deployed Donations
@not_deployed_donations = Donation.not_deployed_sum
# Deployed Donations Percentage
@deployed_donations_percentage = percentage(@deployed_donations, @total_donations_sum)
# Not Deployed Donations Percentage
@not_deployed_donations_percentage = (@not_deployed_donations.to_f / @total_donations_sum.to_f) * 100
# Total Donations
@total_donations = Donation.count
# Paid Donations
@paid_donations = Donation.paid_count
# Unpaid Donations
@unpaid_donations = Donation.unpaid_count
# All Programs
@programs = Program.all
end
end
捐赠模式(初始)
class Donation < ApplicationRecord
belongs_to :program
end
捐赠模型(重构)
Class Donation < ApplicationRecord
belongs_to :program
scope :paid_count, -> { where(payment: true).count }
scope :unpaid_count, -> { where(payment: false).count }
scope :paid_sum, -> { where(payment: true).sum(:amount) }
scope :paid_sum, -> { where(payment: true).sum(:amount) }
scope :deployed_sum, -> { where(deployment: true).sum(:amount) }
scope :not_deployed_sum, -> { where(deployment: false).sum(:amount) }
def percentage(donate, total)
(donate.to_f / total.to_f) * 100
end
end
我需要一些关于 Rails 最佳实践的帮助来解决这些问题,遵循瘦模型和瘦控制器 Rails 原则。
【问题讨论】:
标签: ruby-on-rails rubocop