7

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?

1

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this response. Because of how I have it, the payments aren't directly associated with the contracts, so originally I ignored the idea for accepts_nested_attributes_for. However, I completely forgot about the fields_for helper, which is exactly what I was needing to be able to use the partial (which used formbuilder vars f) without creating another form inside the original form. You led me down the right path!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.