Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Render part of a form inside another form

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?

like image 243
Wes Foster Avatar asked Aug 03 '12 19:08

Wes Foster


1 Answers

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

like image 73
rickypai Avatar answered Nov 09 '22 05:11

rickypai