croceldon
croceldon

Reputation: 4595

How to make Rails 5.2 form submit remotely?

In my view, using Slim:

= form_with url: update_pn_price_path(@price)
  .form-group
    = label_tag :part_number
    = text_field_tag :part_number, @price.part_number, required: true

  .form-group
    => submit_tag t(:save), class: 'btn btn-primary btn-sm'
    = link_to 'Cancel', '', class: 'btn btn-link btn-sm', data: { cancel_in_place: true }

This always submits using a standard submit, not remotely. Log shows:

Processing by PricesController#update_pn as HTML

What am I doing wrong? Why won't it submit using JS?

Upvotes: 1

Views: 376

Answers (2)

croceldon
croceldon

Reputation: 4595

Here's what solved the issue. Rookie mistake, but posting here in case someone else runs into it.

My form shown above was inside another form. You can submit such an 'inner' form, but not remotely. The form was being inserted via an AJAX call, so I changed that to insert to the end of the HTML body, and then positioned using CSS. That put it outside the containing form and made things work as expected.

Upvotes: 4

3limin4t0r
3limin4t0r

Reputation: 21130

I'm surprised to see that your view compiles. There are a few problems that I can spot.

  1. You start indenting content as though it would be in the form. However you didn't open a form tag or provided a block to the form_with method.

    = form_with url: update_pn_price_path(@price)
      .form-group
    

    Should at least be changed to:

    = form_with url: update_pn_price_path(@price) do
      .form-group
    

    Since a variable is provided to a block, the preferred way is to capture it in a variable (form in the code below). If you're not planning to use it you should still capture it in an underscored variable to indicate that it is there, but not being used (_form).

    = form_with url: update_pn_price_path(@price) do |form|
      .form-group
    
  2. Since you're using a form builder, the preferred way of creating elements is through the form builder interface. Since you're not creating the submit tag through the form builder this might be another reason why the submit isn't done remotely.

    I would at least replace:

    => submit_tag t(:save), class: 'btn btn-primary btn-sm'
    

    With:

    = form.submit t('save'), class: 'btn btn-primary btn-sm'
    

    But preferably update the whole form to use the form builder. The result should look something like this:

    = form_with model: @price, url: update_pn_price_path(@price) do |form|
      .form-group
        = form.label :part_number
        = form.text_field :part_number, required: true
    
      .form-group
        = form.submit t('save'), class: 'btn btn-primary btn-sm'
        = link_to 'Cancel', '', class: 'btn btn-link btn-sm', data: {cancel_in_place: true}
    

For more/other form builder methods see the FormBuilder and FormHelper documentation.

Upvotes: 5

Related Questions