我有两个基本型号:
- Account [id, name]
- Balance [id, account_id, date, balance]
他们的控制器包含来自脚手架的默认代码,而且我已经使用'语句修改了余额控制器'功能。这允许我计算存储在余额表中的最近日期的所有帐户的总余额。
目前这很好并按预期工作,我的语句视图显示数据。
但是,如何显示所有“ ”日期的下拉列表。来自'余额'表。然后将balances_controller.rb中的@latestDate设置为下拉列表中的选定日期。
我已尝试在statement.html.erb中添加此内容:
<%= form_for(@balance) do |b| %>
<%= b.label :date %><br>
<%= b.collection_select(:date, @dates, :id, :date) %>
<% end %>
但是,我不确定这是否是正确的方法,这会引发以下错误:
Couldn't find Balance with 'id'=
我的代码:
account.rb
class Account < ActiveRecord::Base
has_many :balances
validates :name, presence: true, length: { maximum: 250 },
uniqueness: { case_sensitive: false }
end
balance.rb
class Balance < ActiveRecord::Base
belongs_to :account
validates :account, presence: true, length: { maximum: 250 }
end
balances_controller.rb
def index
@balances = Balance.all.order(date: :desc)
end
def new
@balance = Balance.new
end
def statement
@dates = Balance.all.order('date desc').dates
@latestDate = Balance.order('date desc').first.date
@summaryBalances = Balance.joins(:account).order('accounts.credit').where('date = :abc', {abc: @latestDate})
@assetTotal = Balance.joins(:account).where('date = :abc', {abc: @latestDate}).where("credit = 'f'").sum(:balance)
@creditTotal = Balance.joins(:account).where('date = :abc', {abc: @latestDate}).where("credit = 't'").sum(:balance)
@worth = @assetTotal - @creditTotal
end
余额/ statement.html.erb
<h1>Statement at <%= @latestDate %></h1>
<p>(showing all balances from the (select top 1 date from balances))</p>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Account</th>
<th>Balance</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>
<% @summaryBalances.each do |balance| %>
<tr>
<% if !(balance.account.credit) %>
<td><%= balance.account.name %></td>
<% else %>
<td><%= balance.account.name + ' (Credit)' %></td>
<% end %>
<td class='account-balance'><%= number_to_currency(balance.balance, unit: "£") %></td>
<td><%= link_to 'Edit', edit_balance_path(balance) %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
<h5>Assets:</h5>
<%= number_to_currency(@assetTotal, unit: "£") %>
<h5>Liabilities:</h5>
<%= number_to_currency(@creditTotal, unit: "£") %>
<h5>Net Worth:</h5>
<%= number_to_currency(@worth, unit: "£") %>
答案 0 :(得分:1)
根据您的评论,只需将before语句添加到before_action,如下所示:
before_action :set_balance, only: [:show, :edit, :update, :destroy, :statement]
由于您也从表单中引用@balances
,因此您需要在控制器上的语句操作中设置它。
def statement
@balances = Balance.all # Or whichever balances you want
# Your existing code here...
end