Dealing with distinct form actions for 'new' and 'edit' in Rails using simple_form, remote_true, and custom controller

I've been following a tutorial on how Ajax works with Ruby on Rails. However, I decided to take a slightly different approach. After setting up a scaffold for 'tasks' (including the controller, model, and views), I created a new controller called 'demo' to experiment with Ajax functionality. This 'demo' controller includes actions for index, new_task, create_task, edit_task, and update_task. I also had to adjust the routes accordingly.

When attempting to render the form (located at app/views/demo/_form.html.erb), I encountered an issue:

<%= simple_form_for @task, remote: true do |f|   %>
  <%= f.input  :description                      %>
  <%= f.input  :deadline                         %>
  <%= f.button :submit                           %>
<% end %>

The form's 'action' was set to '/tasks', which points to 'controller: tasks, action: create'. However, this controller is designed for traditional HTML handling, not for Ajax requests like in the 'demo' controller.

To address this, I added the 'url' parameter as suggested by some resources:

<%= simple_form_for @task, remote: true, url: '/demo/create_task' do |f|   %>
  <%= f.input  :description                      %>
  <%= f.input  :deadline                         %>
  <%= f.button :submit                           %>
<% end %>

This solution worked well for the 'new' and 'create' actions. However, when it came time to UPDATE a model, I ran into a problem. The correct path should be '/demo/update_task'. How should I handle this in Rails?

  1. One suggestion was to determine the URL before rendering the form based on whether the task is new or if it needs to be updated.

  2. Another option proposed using two separate forms for creating and editing to maintain the DRY principle. However, this approach may not be the most efficient.

  3. An alternative, although deemed "ugly", was redirecting from the 'tasks' controller to the 'update_task' action in the 'demo' controller. This solution was not recommended due to the temporary nature of the 'tasks' controller.

Answer №1

After much consideration, I made the decision to include an additional line of code before the form is rendered:

<% url = @task.new_record? ? "/demo/create_task" : "/demo/update_task?id=#{@task.id}" %>
<%= simple_form_for @task, remote: true, url: url do |f|   %>
  <%= f.input  :description                      %>
  <%= f.input  :deadline                         %>
  <%= f.button :submit                           %>
<% end %>

Although it may not be flawless, it definitely gets the job done.

Naturally, there are a few tweaks that need to be made:

  • Include the route patch 'demo/update_task'
  • The method update_task in the Demo controller should reload all tasks after updating attributes

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

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

What is causing the error message of "prop id does not match the rendered server output" to appear on my screen?

https://i.stack.imgur.com/VOLDT.png I've been working on a nextjs redux project and I keep running into this error whenever I refresh my page. Despite searching for a solution, I haven't been able to resolve it. The official next js blog suggest ...

Ways to integrate vanilla JavaScript with VueJS

I am currently working on implementing a vuejs component and could use some guidance. Can anyone provide assistance on where to place the JavaScript code in order for it to function correctly? As a newcomer to vuejs, I am still uncertain about how to prope ...

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Struggling with modifying class in HTML using JavaScript

I've been attempting to replicate a JavaScript code I came across on the internet in order to create a functioning dropdown menu. The concept is quite straightforward - the div class starts as xxx-closed and upon clicking, with the help of JavaScript, ...

How can I delay the loading of a link until the pop-up is closed?

I have successfully implemented a pop-up on my website, but I am facing an issue where I need to prevent any linked pages from loading until the visitor clicks on the accept button. However, I am struggling to make it function as intended. Below is the sn ...

Placing the IconButton within an AppBar Component using React-JS

Trying to position two IconButtons within a Toolbar, one on the right side and the other on the left side. However, both are ending up on the right side. Here's my code: <AppBar position="fixed" > <Toolbar> <Ic ...

There was an error of "Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor"

I've been diving into cannon.js and encountering the following error: Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor. I've tried numerous solutions but none seem to be working. Here's a snippet of my script: var scene, came ...

React Hook Form: Reset function triggers changes across all controllers on the page

I encountered an issue with using the reset function to clear my form. When I invoke the reset function, both of my form selects, which are wrapped by a Controller, get cleared even though I only defined default value for one of them. Is there a way to pr ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Converting ampersands to HTML special characters in AJAX JSON transformations

My PHP script returns a JSON-encoded response like this: //PHP $response = array('type' => 'success', 'content' => '&&!%$#!some words'); echo json_encode($response); return; The JavaScript code then a ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

Reordering CRUD operations in AngularJS

I am currently working with this function: // Check if the object already exists. // If it does, the object is deleted and then created again. save: function(url, obj, errors) { this.get(url, obj); this.create(url, obj, errors); }; Despite the or ...

Combine Vue Plugin Styles without Using Components

Question Time To clarify, when I mention 'without component', I am referring to my plugin being a custom Vue Directive that does not rely on a template. It acts as a wrapper for a class, without the need for an additional component. However, I a ...

Scrapy does not have the capability to send POST requests

I created a Scrapy spider to handle a website with AJAX functionality. It works fine when I manually use fetch() in the Scrapy shell, but when I run "scrapy crawl ...", I don't see any POST requests in the log and no items are being scraped. What coul ...

What is the best way to set up an on-change listener for material-ui's <CustomInput...>?

I'm currently utilizing the React dashboard created by Creative Tim. I have a question regarding how to set up an onChange listener for a Here is the code snippet for the custom input class: import React from "react"; import classNames from "classna ...

Adding row numbers to a table generated by a JQuery DataTable with server-side data source can be achieved by implementing a custom function

Utilizing JQuery and DataTable to display data, I am unable to add row numbers to the grid generated on the client-side. Below is a snippet of my code: HTML <table id="applications_list" class="table table-bordered datagrid"> <thead> ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

Flipping and expanding cards with CSS3

I am attempting to create a layout with a collection of cards/divs within a container. When a card/div is clicked, it should flip horizontally and expand to occupy the entire space within the container (essentially resizing to 100% x 100% when clicked). I ...