请,我真的不知道如何按照最佳的Rails惯例来最佳地重构此代码。我试图在其他控制器的Rails应用程序中调用模型中定义的一些方法。
我有一个捐赠模型和一个仪表板控制器,我想在仪表板上显示一些有关捐赠的数据。我想通过在 Donations模型中的某些方法和范围内定义所需的数据,然后在 Dashboard控制器中调用它们,然后使其在*仪表板视图**。
但是我意识到,关于捐赠的数据没有显示在仪表板上,这可能是由于 Donations模型中的方法未公开或无法用于以下事实的结果仪表板控制器,因为它们是不同的型号和控制器。
这是我的代码
捐赠模式
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 :deployed_sum, -> { where(deployment: true).sum(:amount) }
scope :not_deployed_sum, -> { where(deployment: false, payment: true).sum(:amount) }
def self.deployed_donations_percent
(deployed_sum.to_f / paid_sum.to_f) * 100
end
def self.not_deployed_donations_percent
(not_deployed_sum.to_f / paid_sum.to_f) * 100
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_percent = Donation.deployed_donations_percent
# Not Deployed Donations Percentage
@not_deployed_donations_percent = Donation.not_deployed_donations_percent
@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
仪表板索引
<h2>
DASHBOARD
</h2>
<h4>Overall Donations</h4>
<%#= area_chart @donations.map { |pay|{name: pay.payment, data: @donations.where(payment: pay).group_by_day(:created_at).count}}, discrete: true %>
<%= line_chart Donation.group(:payment).group_by_day(:created_at).count
<h4>Total Donations</h4>
<%= number_with_delimiter(@total_donations_sum, :delimiter => ',') %>
<h4>Deployed</h4>
<%= number_with_delimiter(@deployed_donations, :delimiter => ',') %>
<div>
<%= @deployed_donations_percent.round %>>
</div>
<h4>Undeployed</h4>
<%= number_with_delimiter(@not_deployed_donations, :delimiter => ',') %>
<div>
<%= @not_deployed_donations_percent.round %>
</div>
<h4>Total Donations</h4>
<header>
<%= @total_donations %>
</header>
<h4>Paid Donations</h4>
<header>
<%= @paid_donations %>
</header>
<h4>Unpaid Donations</h4>
<header>
<%= @unpaid_donations %>
</header>
PROGRAMS
<td>Program Name</td>
<td>Sponsored</td>
</tr>
<% @programs.each do |program| %>
<tr>
<td><%= program.name %></td>
<td><%= program.donations.count %></td>
请,我将非常感谢您提供一些有关如何重构此代码并将 Donations模型方法公开给 Dashboard Controller 的帮助。谢谢。
答案 0 :(得分:1)
您也可以尝试一下。
控制器和模型有一个名为关注点的文件夹,您可以在其中保存要由不同控制器和/或模型共享的代码。
只需将要共享的代码移动到关注文件夹,然后在每个模型上调用它们。
您可以使用模块在关注文件夹中定义代码。
答案 1 :(得分:0)
最后,我明白了。
我需要使用Plain Old Ruby Objects实现服务对象。 对于每个操作,我将它们放在单独的服务中,然后在控制器中对其进行调用。
步骤是
仅此而已。