I have a page in which you create an invoice. There is a separate section that allows you to add payments to invoices. What I'm wanting to do is add the ability to create a payment when creating an invoice.
I'm wanting to render the "Create Payment" form VIEW into the "Create Invoice" form VIEW. How can I do this? Here is some code:
Invoice Form view (notice the render call):
<%= form_for(@contract) do |f| %>
<div class="field">
f.label "Add payment?"
<div id="pay_form">
<%= render 'payments/pay_form' %>
</div>
</div>
(_pay_form.html.erb) The partial from the create payment form (notice I'm not including the form_for tag here because I don't want to next a form inside of another form on the Invoice page above):
<div class="field">
<%= f.label 'Amount Paid:' %>
<%= f.text_field :amount %>
</div>
<div class="field">
<%= f.label 'Payment Method' %>
<%= f.select :method, %w(Cash Credit Check) %>
</div>
The main problem is the f
variable in the partial doesn't exist. And even if I assign the Invoice's f
var from it's form, the names of the params would be params[:invoice][:amount]
rather than params[:payment][:amount]
. See what I'm saying?
What's the best way to go about doing this?
You need to pass the f
variable from the view to the partial.
To do this, change
<%= render 'payments/pay_form' %>
into
<%= render 'payments/pay_form', f: f %>
Should you encounter name errors, since both are named f
try:
<%= render :partial => 'payments/pay_form', :locals => { :f => f} %>
or
<%= form_for(@contract) do |builder| %>
<div class="field">
builder.label "Add payment?"
<div id="pay_form">
<%= render 'payments/pay_form', f: builder %>
</div>
</div>
Hope this helps.
For further learning, I think what you are really looking for is nested forms.
Here are some good tutorials on this subject, if you are interesting in learning about them:
http://railscasts.com/episodes/196-nested-model-form-part-1 http://railscasts.com/episodes/197-nested-model-form-part-2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With