2

我有这样的表格payments

<%= f.label :invoice_id %>
<%= f.select(:invoice_id, current_user.outstanding_invoices_collection) %>

<%= f.label :amount %>
<%= f.text_field :amount %>

我想知道是否有办法以某种方式填充amount文本字段的值,例如使用关联的未结余额invoice

在我的Invoice模型中有这个功能:

def balance
  payments.map(&:amount).sum - total
end

如何才能做到这一点?

4

2 回答 2

2

我假设您要根据从下拉列表中选择的发票来填充文本框。在这种情况下

这个想法是

  • 您需要对发票下拉列表进行 ajax 调用。
  • 该 ajax 响应应该更新文本框的值。

对于 rails-3,我认为它建议以不可靠的方式执行此操作。这是您可以关注的链接。开始玩它,同时我会尝试做一些功能性的东西。希望再次取得好成绩。

您是否正在寻找如何仅填充值?

更新:

这是ajax部分

#Application.js or any sutable js file
$(function($) {
    $("#your_drop_down_id").change(function() {
        #Your the url to your controller action here
        $.ajax({url: '/get_amount',
        data: 'invoice_id=' + this.value,
        dataType: 'script'})
    });
});

#in get_amount Action
invoice = Invoice.find(params[:invoice_id]) #Other appropriate logic to get the invoice
@amount = invoice.balance

#get_amount.js.erb
$('#your_text_box_id').val('<%= @amount %>');

#routes.rb
#This part is written following the gist: https://gist.github.com/3889180 by @TinTin
resources :payments do  
   collection do
       get 'get_amount'
   end
end

让我知道是否有任何部分让您感到困惑。

于 2012-10-14T15:43:51.480 回答
1

在您的控制器中,您可以为任何字段分配任何值,它将显示在视图中。

def new
  @payment = new Payment()
  @payment.amount = 100
end

如果您想要一些动态值,例如:基于组合框选择,然后在 javascript 或 AJAX 中执行。

于 2012-10-14T15:43:19.030 回答