Jamesla
Jamesla

Reputation: 1408

How do I disable rails form_with update functionality

I have the following form to add somebody to a waiting list.

<%= form_with(model: waitinglist, url: '/join', local: true) do |form| %>
  <div class="field">
    <%= form.text_field :email %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

This works fine and it will post and add somebody to the waiting list. However when the page reloads the form goes into some sort of automatic resource mode that where the submit button magically changes to update and then the form submit magically changes to the HTTP Patch method.

I'm trying to understand what is doing this and I can't find anything in the docs.

How do I create a regular form that just posts to an end point but still validates the model? (and removes this update functionality).

edit added controller

class WaitinglistsController < ApplicationController
  before_action :set_waitinglist, only: [:show, :edit, :update, :destroy]

  # GET /waitinglists/new
  def new
    @waitinglist = Waitinglist.new
  end

  # POST /waitinglists
  # POST /waitinglists.json
  def create
    @waitinglist = Waitinglist.new(waitinglist_params)

    if @waitinglist.save
      flash[:notice] = "You have been added to the waiting list"
      render :new
    else
      render :new
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_waitinglist
    @waitinglist = Waitinglist.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def waitinglist_params
    params.require(:waitinglist).permit(:email)
  end
end

Upvotes: 0

Views: 401

Answers (2)

Cir&#233; Dia
Cir&#233; Dia

Reputation: 1

I think what u should do is if the waiting list is saved, redirect to new instead of render new. When u redirect to action it will call the action so a new object will be created. When u do render it render the view and I will have your persisted object, that’s why it is trying to update.

Upvotes: 0

Jonathan Bennett
Jonathan Bennett

Reputation: 1065

You are keeping a copy of your persisted waitinglist variable around between page loads. When your new page is rendered for the second time, since the waiting list has already been persisted, it is doing all the magical default Rails behaviours, which include updating labels for the submit button (create vs update), and the form's method (post vs patch).

You will want to create a new waitinglist if you are going to re-render the new page:

  def create
    @waitinglist = Waitinglist.new(waitinglist_params)

    if @waitinglist.save
      @waitinglist = Waitinglist.new # 
      flash[:notice] = "You have been added to the waiting list"
      render :new
    else
      render :new
    end
  end

Upvotes: 1

Related Questions