Rails Render part of a form inside another form

I have a page on which you create an invoice. There is a separate section that allows you to add payments to invoices. What I want to do is add the ability to create a payment when creating an invoice.

I want to display the VIEW Create Payment form in the VIEW Create Account form. How can i do this? Here is the code:

Type of account form (pay attention to the rendering 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) Partially from the payment creation form (a notice that I do not include here in the form_for tag because I do not want the next form inside 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 that the variable f does not exist in the partial. And even if I assign Invoice f var from its form, the parameter names will be params[:invoice][:amount] , not params[:payment][:amount] . See what I'm saying?

What is the best way to do this?

+6
source share
1 answer

You need to pass the variable f from the view to partial.

To do this, change

 <%= render 'payments/pay_form' %> 

in

 <%= render 'payments/pay_form', f: f %> 

If you encounter name errors, since both are called f

to 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 training, I think you are really looking for nested forms.

Here are some good guides on this subject if you are interested in learning about them:

http://railscasts.com/episodes/196-nested-model-form-part-1 http://railscasts.com/episodes/197-nested-model-form-part-2

+7
source

Source: https://habr.com/ru/post/922080/


All Articles