【发布时间】:2018-01-21 22:05:08
【问题描述】:
我正在开发 Rails 应用程序以支付费用。
基本上我会输入一些费用,给出名称、描述、金额、货币和日期。
为此,我有 3 个模型:用户、支出、货币与此关系:
class Currency < ApplicationRecord
has_many :spendings
has_many :users, through: :spendings
end
class Spending < ApplicationRecord
belongs_to :user
belongs_to :currency
end
class User < ApplicationRecord
has_many :spendings
has_many :currencies, through: :spendings
end
我正在使用 users_controller 中的节目来索引每个用户的费用。这就是我的 users_controller 中的内容
class UsersController < ApplicationController
def show
@user_spendings = @current_user.spendings.all.order('date DESC').paginate(:page => params[:page], :per_page => 10)
@user_amount = @user_spendings.sum(:amount)
end
end
在这种情况下,@user_amount 向我显示了 current_user 的所有费用,问题是我有 2 种货币(将来可能会更多),我想显示不同的总金额,具体取决于何时选择了哪种货币我创建了一项新费用。
我在这里考虑了不同的事情,我尝试做一个 If 语句,以便仅当 currency_id == 为 1 (如果€)或 2 (如果 $ 等)时显示金额...但是如果我添加新货币(和我无法让它工作)。
也许是一个循环?循环浏览货币并以某种方式显示总金额。但是你不能循环求和所以我不知道。
我也希望它灵活,所以如果将来我添加更多货币,我不必接触代码。
有什么想法吗?
如果需要这里是我的 show.html.erb
<% @user_spendings.each do |spending| %>
<tr>
<td><%= spending.title %></td>
<td><%= spending.description %></td>
<td><%= '%.02f' % spending.amount %></td>
<td><%= spending.currency.symb %></td>
<td><%= spending.date.strftime('%d %B %Y') %></td>
</tr>
<% end %>
非常感谢。
【问题讨论】:
-
我发现了类似的东西:Spending.where(id: Currency.where(name: 'Euro').select(:spending_id)).sum(:amount) 但它显示我为 0结果:(
标签: ruby-on-rails sum ruby-on-rails-5 currency calculation