如何计算Ruby on Rails中表单文本字段的默认值?

时间:2012-10-14 15:18:29

标签: ruby-on-rails ruby-on-rails-3

我有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

如何做到这一点?

2 个答案:

答案 0 :(得分:2)

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

这个想法是

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

对于rails-3,我认为它建议以无创意的方式做到这一点。 Here is a link you can follow。开始玩它同时我会尝试做一些功能。希望能再次获得好成绩。

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

<强>更新

这是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

如果有任何部分让您感到困惑,请告诉我。

答案 1 :(得分:1)

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

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

如果你想要一些动态值,例如:基于组合框选择,那么在javascript或AJAX中进行。