У меня есть таблица, где я зацикливаюсь на affiliate_sales, которая дает мне большую часть данных, которые мне нужны, за исключением вычисления общего итога столбца «Всего заработано».
<thead>
<tr>
<td><strong>Model Name</strong></td>
<td><strong>Subscriber's Email</strong></td>
<td><strong>Subscription Amount</strong></td>
<td><strong>Your Share</strong></td>
<td><strong>Lifetime *</strong></td>
<td><strong>Date Started</strong></td>
<td><strong>Date Canceled</strong></td>
<td><strong>Payments</strong></td>
<td><strong>Total Earned</strong></td>
</tr>
</thead>
<tbody>
<% @affiliate_sales.each do |sales| %>
<!-- figure out number of payments made -->
<% if sales.active? && sales.lifetime.blank? %>
<% active_payments = ((Date.today.year * 12 + Date.today.month) - (sales.created_at.year * 12 + sales.created_at.month) + 1) %>
<% end %>
<% if sales.active === false && sales.lifetime.blank? %>
<% canceled_payments = ((sales.end_date.year * 12 + sales.end_date.month) - (sales.created_at.year * 12 + sales.created_at.month)) %>
<% end %>
<!-- end payments calc -->
<% if active_payments.present? %>
<% total_active_payments = (sales.cost * 0.25) * (active_payments) %>
<% end %>
<% if canceled_payments.present? %>
<% total_canceled_payments = (sales.cost * 0.25) * (canceled_payments) %>
<% end %>
<tr>
<td><%= sales.model.stage_name %></td>
<td><%= sales.user.email %></td>
<td><%= number_to_currency(sales.cost) %></td>
<td><%= number_to_currency(sales.cost * 0.25) %></td>
<td>
<% if sales.lifetime? %>
yes
<% else %>
no
<% end %></td>
<td><%= Time.at(sales.created_at).to_datetime.strftime("%B %d, %Y") %></td>
<% if sales.end_date.present? %>
<td><%= Time.at(sales.end_date).to_datetime.strftime("%B %d, %Y") %></td>
<% else %>
<td>active</td>
<% end %>
<!-- start of column payments -->
<% if active_payments.present? %>
<td><%= active_payments %></td>
<% end %>
<% if canceled_payments.present? %>
<td><%= canceled_payments %></td>
<% end %>
<!-- end of number of payments made -->
<!-- start total earned -->
<% if total_active_payments.present? %>
<td><%= number_to_currency(total_active_payments) %></td>
<% end %>
<% if total_canceled_payments.present? %>
<td><%= number_to_currency(total_canceled_payments) %></td>
<% end %>
<!-- end total of payments -->
</tr>
<% end %>
<tr class="totals">
<td>Totals</td>
<td></td>
<td></td>
<td><%= number_to_currency @affiliate_sales_total %></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
Один из моих расчетов - выяснить, сколько ежемесячных платежей было сделано подписчиком, что я успешно делаю с переменными active_payments и cancelled_payments в моем цикле.
Оттуда я умножаю количество платежей, сделанных на стоимость подписки, на процент от аффилиатов, что дает мне «общее количество заработанных (total_active_payments и total_canceled_payments) по каждой подписке для партнера.
В моей строке «итогов» (вне цикла) я использую метод в моем affiliate_sites_controller, который вычисляет общую стоимость подписок:
def affiliate_sales
if current_user.affiliate_sites.present?
Subscription.where(teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token)
end
end
def affiliate_canceled_subs
if current_user.affiliate_sites.present?
Subscription.where(active: false, teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token)
end
end
def affiliate_sales_total
if current_user.affiliate_sites.present?
affiliate_sales.sum(:cost) * 0.25
end
end
Я пытаюсь решить проблемычтобы сложить столбец «Всего заработано» как общий итог. Поскольку я не могу получить доступ к этой переменной за пределами цикла, есть ли другой способ выяснить это?
Вот мой контроллер:
before_action :authenticate_user!
def new
@affiliate_site = current_user.affiliate_sites.new
end
def show
@affiliate_site = current_user.affiliate_sites.first
@affiliate_site_token = affiliate_site_token
@affiliate_sales = affiliate_sales
@affiliate_sales_total = affiliate_sales_total
@progress_bar = percentage_to_payout
@affiliate_canceled_subs = affiliate_canceled_subs
end
def create
@affiliate_site = current_user.affiliate_sites.new(affiliate_site_params)
if @affiliate_site.save
# send_model_application_email
redirect_to profile_path(current_user), notice: "Your Affiliate information has been successfully submitted!"
else
render :new
end
end
def edit
@affiliate_site = current_user.affiliate_sites.first
end
def update
@affiliate_site = current_user.affiliate_sites.first
if @affiliate_site.update(affiliate_site_params)
redirect_to affiliate_site_path(current_user.affiliate_sites.first), notice: "Your information has been successfully updated!"
else
render :edit
end
end
def affiliate_site_token
if current_user.affiliate_sites.present?
current_user.affiliate_sites.first.affiliate_site_token
end
end
def affiliate_sales
if current_user.affiliate_sites.present?
Subscription.where(teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token)
end
end
def affiliate_canceled_subs
if current_user.affiliate_sites.present?
Subscription.where(active: false, teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token)
end
end
def affiliate_sales_total
if current_user.affiliate_sites.present?
affiliate_sales.sum(:cost) * 0.25
end
end
def affiliate_rebills
active_subscriptions = Subscription.where(teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token, active: true, lifetime: [false, nil])
# figure out number of months it has rebilled
(Date.today.year * 12 + Date.today.month) - (active_subscriptions.created_at.year * 12 + active_subscriptions.created_at.month)
end
def rebills_before_canceled
canceled_subscriptions = Subscription.where(teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token, active: false, lifetime: [false, nil]) && Subscription.end_date?
(canceled_subscriptions.end_date.year * 12 + canceled_subscriptions.end_date.month) - (canceled_subscriptions.created_at.year * 12 + canceled_subscriptions.created_at.month)
end
def percentage_to_payout
if current_user.affiliate_sites.present?
result = (affiliate_sales_total / 50.0) * 100
return result.to_s.at(0..4) + '%'
end
end
private
def affiliate_site_params
params.require(:affiliate_site).permit(:full_name, :company_name, :tax_id, :affiliate_site_token, :website, :email, :user_id, :affiliate_terms)
end
end
РЕДАКТИРОВАТЬ: Итак, я смог выяснить это. После рефакторинга моего логического представления я создал 2 метода в моей модели subscription.rb, чтобы рассчитать количество платежей, совершенных подписчиком:
def total_active_payments
((Date.today.year * 12 + Date.today.month) - (created_at.year * 12 + created_at.month) + 1)
end
def canceled_subscription_payments
((end_date.year * 12 + end_date.month) - (created_at.year * 12 + created_at.month))
end
затем я добавил 2 новых метода в свой контроллер:
def grand_total_active_payments
grand_total_active_payments = 0
Subscription.where(teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token, active: true).each do |sub|
grand_total_active_payments += ((sub.cost * 0.25) * sub.total_active_payments)
end
grand_total_active_payments
end
def grand_total_canceled_payments
grand_total_canceled_payments = 0
Subscription.where(teddys_affiliate_site_token: current_user.affiliate_sites.first.affiliate_site_token, active: false).each do |sub|
grand_total_canceled_payments += ((sub.cost * 0.25) * sub.canceled_subscription_payments)
end
grand_total_canceled_payments
end
затем я просто добавил эти два инстаNces вместе на мой взгляд:
<tr class="totals">
<td>Totals</td>
<td></td>
<td></td>
<td><%= number_to_currency @affiliate_sales_total %></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><%= number_to_currency(@grand_total_active_payments + @grand_total_canceled_payments) %></td>
</tr>