我对rails相对较新,并试图编写一个小额贷款应用程序,用户可以向某人提供贷款,此应用程序可以跟踪余额/等等。我正在为处理付款的贷款模型添加一个功能到目前为止(提请注意make_payment(value)
部分:
class Loan < ActiveRecord::Base
belongs_to :lender, :class_name => 'User'
belongs_to :borrower, :class_name => 'User'
has_many :payments
default_scope -> { order(created_at: :desc) }
validates :amount, presence: true
validates :lender, presence: true
validates :borrower, presence: true
def make_payment(value)
remainder = amount - value
update_attribute(:amount, remainder)
return remainder
end
end
我可以使用它来正确地从原始贷款金额中扣除一个值,但我似乎无法使用视图和表单使其工作。目前我的观点如下:
<p id="notice"><%= notice %></p>
<div class="row">
<div class="col-md-2">
<ul>
<li><strong>Lender</strong>: <%= @loan.lender.username %></li>
<li><strong>Borrower</strong>: <%= @loan.borrower.username %></li>
<li><strong>Amount Remaining</strong>: <%= @loan.amount %></li>
</ul>
<section>
<div class="col-md-6 col-md-offset-3">
<%= form_for @loan do |f| %>
<%= f.label :make_payment %> <!--confusion -->
<%= f.number_field :value, class: 'form-control' %> <!--confusion -->
<%= f.submit "Submit Payment", class: "btn btn-primary" %>
<% end %>
</div>
</section>
</div>
</div>
<%= link_to 'Edit', edit_loan_path(@loan) %> |
<%= link_to 'Back', loans_path %>
当我尝试访问该页面时,我得到一个错误wrong number of arguments (0 for 1)
,这完全合理,但我希望表单中提交的值是函数{{1}的参数(值) }。我应该完全使用make_payment(value)
还是别的什么?我确信这是一个简单的修复,我似乎无法找到我正在寻找的答案。
答案 0 :(得分:0)
一个不错的RESTful解决方案可能如下所示:
resources :loans, shallow: :true do
resources :payments, only: :create
end
class PaymentsController < ApplicationController
# POST /loans/:loan_id/payments
def create
@loan = Loan.find(params[:loan_id])
@loan.make_payment(payment)
if @load.save
redirect_to @loan, notice: "Payment successful"
else
redirect_to @loan, alert: "Payment count not be processed"
end
end
private
def payment
require(:loan).require(:payment)[:payment]
end
end
然后你的表格看起来像这样:
<%= form_for @loan, url: loan_payments_path(loan: @loan), method: :post do |f| %>
<%= f.label :payment %>
<%= f.number_field :payment, class: 'form-control' %>
<%= f.submit "Submit Payment", class: "btn btn-primary" %>
<% end %>