Reputation: 10207
I have a form for payments
like this:
<%= f.label :invoice_id %>
<%= f.select(:invoice_id, current_user.outstanding_invoices_collection) %>
<%= f.label :amount %>
<%= f.text_field :amount %>
I wonder if there's a way to populate the value of the amount
text field somehow, e.g. with the open balance of the associated invoice
?
In my Invoice
model have this function:
def balance
payments.map(&:amount).sum - total
end
How can this be done?
Upvotes: 2
Views: 1240
Reputation: 5317
Im assuming you want to populate the text box based on the selection of a invoice from dropdown. In that case
The idea is
And with rails-3 i think its recommended to do this in unrobustive way. Here is a link you can follow. Start playing with it meanwhile I will try to make something functional. Hope to get a good result again.
Are you looking for how to populate the value only?
Update:
Here is the ajax part
#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
Let me know if any part is confusing to you.
Upvotes: 2
Reputation: 13925
In your controller you can assign any value to any field, and it will be displayed in the view.
def new
@payment = new Payment()
@payment.amount = 100
end
If you want some dynamic value, e.g: based on a combobox selection, then do it in javascript or with AJAX.
Upvotes: 1