Using the PATCH method in Rails instead of POST

i have some code to display here

<%= form_for @campaign, url: brands_campaign_path(@campaign), method: :patch,  :html => {:multipart => true, :class => 'form-horizontal'} do |f| %>

and it generates the following

<form class="form-horizontal" id="edit_campaign_25" enctype="multipart/form-data" action="/campaigns/testing" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="&#x2713;" />
<input type="hidden" name="_method" value="patch" />
<input type="hidden" name="authenticity_token" value="Ybl3G26TZumVbbCew2EmlVxq4Dv2JZx5PAq1Q7nup3vp0GdkT72oIlV==" />

However, despite this setup, I am receiving a POST request on the server-side. The jquery_ujs.js file is also loading properly in the browser.

rake routes

 brands_campaigns GET    /campaigns(.:format)                                         brands/campaigns#index {:subdomain=>"brands"}
                                                      POST   /campaigns(.:format)                                         brands/campaigns#create {:subdomain=>"brands"}
                                  new_brands_campaign GET    /campaigns/new(.:format)                                     brands/campaigns#new {:subdomain=>"brands"}
                                 edit_brands_campaign GET    /campaigns/:id/edit(.:format)                                brands/campaigns#edit {:subdomain=>"brands"}
                                      brands_campaign GET    /campaigns/:id(.:format)                                     brands/campaigns#show {:subdomain=>"brands"}
                                                      PATCH  /campaigns/:id(.:format)                                     brands/campaigns#update {:subdomain=>"brands"}
                                                      PUT    /campaigns/:id(.:format)                                     brands/campaigns#update {:subdomain=>"brands"}
                                                      DELETE /campaigns/:id(.:format)                                     brands/campaigns#destroy {:subdomain=>"brands"}
                               brands_campaigns_posts GET    /campaigns/:id/posts(.:format)                               brands/campaigns#posts {:subdomain=>"brands"}
                             brands_campaigns_details GET    /campaigns/:id/details(.:format)                             brands/campaigns#details {:subdomain=>"brands"}
                         brands_campaigns_influencers GET    /campaigns/:id/influencers(.:format)                         brands/campaigns#influencers {:subdomain=>"brands"}
                 brands_campaigns_submit_for_approval GET    /campaigns/:id/submit_for_approval(.:format)                 brands/campaigns#submit_for_approval {:subdomain=>"brands"}
                    brands_campaigns_pending_to_draft GET    /campaigns/:id/pending_to_draft(.:format)                    brands/campaigns#pending_to_draft {:subdomain=>"brands"}
                              brands_campaigns_cancel GET    /campaigns/:id/cancel(.:format)                              brands/campaigns#cancel {:subdomain=>"brands"}
                         brands_campaigns_add_credits GET    /campaigns/:id/add_credits(.:format)                         brands/campaigns#add_credits {:subdomain=>"brands"}

logs

ActionController::RoutingError (No route matches [POST] "/campaigns/testing/edit"):   actionpack (4.2.5.2) 
lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'   rollbar (2.14.0)
lib/rollbar/middleware/rails/show_exceptions.rb:22:in `call_with_rollbar'   web-console (2.3.0) 
lib/web_console/middleware.rb:20:in `block in call'   web-console (2.3.0) 
lib/web_console/middleware.rb:18:in `catch'   web-console (2.3.0) 
lib/web_console/middleware.rb:18:in `call'   actionpack (4.2.5.2) 
lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'   railties (4.2.5.2)
lib/rails/rack/logger.rb:38:in `call_app'  railties (4.2.5.2) 
lib/rails/rack/logger.rb:20:in `block in call'   activesupport (4.2.5.2) 
lib/active_support/tagged_logging.rb:68:in `block in tagged'   activesupport (4.2.5.2)
lib/active_support/tagged_logging.rb:26:in `tagged'   activesupport (4.2.5.2) 
lib/active_support/tagged_logging.rb:68:in `tagged'   railties (4.2.5.2) 
lib/rails/rack/logger.rb:20:in `call'   actionpack (4.2.5.2) 
lib/action_dispatch/middleware/request_id.rb:21:in `call'   rack (1.6.5) 
lib/rack/methodoverride.rb:22:in `call'   rack (1.6.5) 
lib/rack/runtime.rb:18:in `call'   activesupport (4.2.5.2) 
lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'   rack (1.6.5)
lib/rack/lock.rb:17:in `call'   actionpack (4.2.5.2) 
lib/action_dispatch/middleware/static.rb:116:in `call'   rack (1.6.5) 
lib/rack/sendfile.rb:113:in `call'   railties (4.2.5.2) 
lib/rails/engine.rb:518:in `call'   railties (4.2.5.2) 
lib/rails/application.rb:165:in `call'   rack (1.6.5) 
lib/rack/tempfile_reaper.rb:15:in `call'   rack (1.6.5) 
lib/rack/lint.rb:49:in `_call'   rack (1.6.5)
lib/rack/lint.rb:37:in `call'   rack (1.6.5) 
lib/rack/showexceptions.rb:24:in `call'   rack (1.6.5) 
lib/rack/commonlogger.rb:33:in `call'   sinatra (1.4.7) 
lib/sinatra/base.rb:219:in `call'   rack (1.6.5) 
lib/rack/chunked.rb:54:in `call'   rack (1.6.5) 
lib/rack/content_length.rb:15:in `call'   unicorn (5.2.0) 
lib/unicorn/http_server.rb:562:in `process_client'   unicorn (5.2.0) 
lib/unicorn/http_server.rb:658:in `worker_loop'   unicorn (5.2.0) 
lib/unicorn/http_server.rb:508:in `spawn_missing_workers'   unicorn (5.2.0)
lib/unicorn/http_server.rb:132:in `start'   unicorn (5.2.0) 
bin/unicorn:126:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/bin/unicorn:23:in `load'   
/usr/local/rvm/gems/ruby-2.3.1/bin/unicorn:23:in `<main>'   
/usr/local/rvm/gems/ruby-2.3.1@global/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.3.1@global/bin/ruby_executable_hooks:15:in `<main>'

What Route it should hit as it does on Firefox

Started PATCH "/campaigns/testing" for 106.51.30.182 at 2017-02-06 11:18:02 -0500

Answer №1

According to the provided documentation:

The recommended method for submitting the form is typically either "get" or "post". In cases where "patch", "put", "delete", or another verb is utilized, a hidden input named _method is included to emulate the specified verb over post.

source : http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

as exemplified in the code snippet from your query


<input type="hidden" name="_method" value="patch" />
simulates the patch method instead of post

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Icon dropdown in Bootstrap

Looking for a solution to modify this dropdown using only bootstrap classes. Instead of the current text "Dropleft" and left arrow icon, how can I replace it with an icon fas fa-ellipsis-h? <button type="button" class="btn btn-secondary ...

Validating a single field for City, State, and ZIP in jQuery/JavaScript

I am trying to validate an input field that requires City, State (two letter abbreviation), and ZIP code (5 numeric digits) in the format 'City, State ZIP'. Could someone please help me with validating this specific format and characters? Appre ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

concealed highcharts data labels

I attempted to create a bar chart using Highcharts, and initially it worked fine. However, I encountered an issue when displaying multiple indicators - the datalabels for certain data points are hidden. For example, the datalabel for "provinsi aceh" is not ...

React application experiencing Unhandled Promise Rejection (RangeError): Call stack size limit reached

For my first form in ReactJS, I used a functional app and successfully implemented basic validations. I've also created a function to handle form submission to the backend. But upon clicking submit, I encountered the following error: enter image desc ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

I would greatly appreciate your assistance in creating a regular expression in JavaScript

I need assistance with creating a JavaScript regular expression that matches the format "APL-101". 1) The letters before '-' must be in capital letters, without any special characters, and can be any length. 2) After '-', the string s ...

Step-by-step guide for creating a "load more on scroll" feature with Node.js and MongoDB

I currently have a Node server utilizing Express+Typescript to connect to a MongoDB database using Mongoose. Within the database, there is a collection named Products that the frontend (Angular 9) requests in order to display them. At the moment, the serv ...

Understanding the concept of scope in Javascript is crucial when working with ajax post requests and functions

Looking to improve my JavaScript skills, I've started working with a restful API that provides me with a JSON string. I'm able to successfully parse the information using the following code snippet: $.ajax({ url: './php/bandwidth.php& ...

Ways to determine if an array with a mix of data types includes string values

Challenge I'm Currently Tackling: To solve this challenge, create a function named "findShortestWordAmongMixedElements". The task is to find and return the shortest string from an array that contains mixed element types. Important Notes: * In c ...

What is the best way to define a variable within a function?

Here's a function designed to verify if the username has admin privileges: module.exports = { checkAdmin: function(username){ var _this = this; var admin = null; sql.execute(sql.format('SELECT * FROM tbl_admins'), (err, result, fields ...

What could be causing my Three.js code to fail during testing?

Recently, I decided to delve into the world of Three.js by following a thorough tutorial. While everything seemed perfectly fine in my code editor of choice (Visual Studio Code 2019), I encountered a frustrating issue when I attempted to run the code and n ...

Kindly utilize the POST method for your request

After running the script below, I encountered an error message stating "Please use POST request". As a beginner in HTML and JavaScript, I am unsure of what is causing this issue. Can anyone provide guidance on what may be wrong? Javascript function subm ...

WordPress AJAX code encountered a http400 Bad Request

I've recently started delving into website development and am currently working on a WordPress site. The issue I'm facing is similar to another query on SO, but that question doesn't involve jQuery.AJAX; instead, it utilizes jQuery.post with ...

I currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user ' ...

AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the t ...

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

Determine the coordinates of the mouse cursor within a specific div element

Similar Questions: Determining Mouse Position Relative to a Div Getting the Mouse Position Using JavaScript in Canvas Is there a way to retrieve the mouse position within a canvas element with fixed dimensions and automatic margin? I am unable to ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

Utilizing multiple components onEnter with React-router for authentication scenarios

I am currently working on an app that consists of 2 components for a single path. The routes are as follows: <Router history={hashHistory}> <Route path="/" component={AppContainer} onEnter={requireEnter}> <Route path="/homepage" ...