Utilizing Jbuilder to send a POST request to an API within a Ruby On Rails application

In my project, I have implemented a separation between Backend and Frontend using Rails for the backend and ReactJS for the frontend.

For handling async processing of POST requests, I use the gem Jbuilder to generate JSON APIs.

Here is an example of how I handle a POST request in JavaScript:

fetch('shops/1/deals',{
      method: "POST",
      body: JSON.stringify({shop_id: 1, deals_type: "workout"}),
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
      },
    })
    .then(function(res){ 
      console.log(res)
      res.json().then(function(data){
       alert( JSON.stringify( data ) ) 
     })
})

Below are snippets from the controller:

def index 
 @shop = Shop.find(params[:id])
 @deals = @shop.deals
end

def create
 @deal = Deal.new(deal_params)
 respond_to do |format|
  if @deal.save
   format.json { render :show, status: :created, location: @deal }
  else
   format.json { render json: @deal.errors, status: :unprocessable_entity }
  end
 end
end

If there is a _deal.json.jbuilder file in the views/deals directory, I will receive a specific JSON structure in the alert message.

json.extract! deal, :id, :shop_id, :deals_type, :created_at, :updated_at, :deal_time

However, if I delete the _deal.json.jbuilder file, I will get an empty object ({}) instead. This raises the question: why is this happening?

Answer №1

When you see this code:

format.json { render :show, status: :created, location: @deal }

In Rails, it means that the show view will be rendered for JSON output. This usually corresponds to the

app/views/deals/show.json.jbuilder
file, which in turn renders the _deal partial. If you delete the partial, it will make the view definition invalid.

Therefore, avoid deleting the partial unless you are willing to update other templates referencing it.

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

SQL Server 2016 is throwing an error due to syntax issues with 'JSON'

After recently installing SQL Server 2016 CTP3 for its JSON output feature, I attempted to use it in my SQL Query following the example provided on MSDN. However, when using the keyword JSON in my query, it did not turn blue and instead gave an error messa ...

Defining an empty multidimensional array involves declaring a variable that can store

I am working on a Vue.js project and need to implement a multidimensional array model Here is a Fiddle with my code: In my Vue.js data, I have defined an array like this: new Vue({ el: '#app', data: { message: 'Hello Vue.js!' ...

Spheroidal surface texture appears blurry following software update

Since updating from r67 to r86, our soccer balls don't look as sleek. Has anyone encountered a similar problem before? The code that previously gave us smooth spheres is now causing issues with the texture (and some lighting, but that's manageab ...

Creating a Sticky Table Header with Dynamic Height in React using Material-UI

I am currently utilizing the Material-UI library in React to present a table on my webpage. My goal is to have a sticky header on the table without specifying a fixed height, allowing it to scroll along with the page. However, the code snippet provided doe ...

Tips for simultaneously indexing multiple properties on a JavaScript object

Imagine having a JavaScript object structured like this: var x = { 'one': 1, 'two': 2, 'three': 3 } Now, suppose you have an array containing the specific keys you want to access from this object. Here are the keys you ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

What is the best method for transferring state between a page and a component, and then back to the page

Is there a way to manage state without using Redux in my home.js page (using hooks, not classes), so that I can set/use a state, pass it to my component MyComponent.js, and update the state when a div is clicked inside this component (reflecting the change ...

Creating a Unique Window Design with List View Component in Kendo UI

I am trying to create a customized Kendo Window with two Kendo List Views, an Add button, and a Remove button inside. Right now, my main goal is to display a list of data in the List view within the Kendo Window. Below is the JavaScript code I have: ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

Problem with JQuery binding

Currently, I have set up my radio buttons with jQuery bind using the code below: jQuery().ready(function() { jQuery("input[name='rank_number']:radio").bind('change', function(){ submitSelectedRank(); }); }); While th ...

The value of req.body becomes null following a post request

I've been working on creating a contact form with the help of nodemailer. When trying to submit it using the fetch API, I encountered an issue where req.body is being returned as undefined. Below is the frontend code snippet: form.onsubmit = functio ...

Generate JSON based on identical values within the viewport

I am seeking to establish a new view within my PostgreSQL schema that is based on the following table : +--------------+ | id | date | +-----|--------+ | A | 2012 | | A | 2012 | | A | 2013 | +--------------+ The desired outcome in my view ...

Establish characteristics for the temporary print document

Struggling to configure the properties of a temporary file created for later printing by the user. Here's a breakdown of the process: User clicks on "Print Map Area" button on the website. A menu appears asking for preferred dimensions (e.g. A4 ...

Modify the color of a set of div elements when clicked

Is there a way to change the background color of all divs with a common attribute value (#id for example) after clicking on one of the divs that shares the same attribute value? This is what I have tried so far: $('.group').click(function(){ ...

Is there a way for JavaScript to automatically detect various display sizes and redirect users to different websites based on their screen dimensions?

I recently completed a new website and noticed that it looks quite strange on mobile devices, with overlapping divs causing issues. I tried implementing this code: window.addEventListener("resize", function(){ var width = window.innerWidth || ...

Updating Laravel store function to modify returned data

It seems like there might be an issue in my approach, but I can't pinpoint what or where exactly. Currently, I have a Laravel controller that manages an ajax post request and sends back the results of a curl request to that ajax call: public functio ...

Obtain the current name of the Material UI breakpoint

Looking for a MUI function called MaterialUIGiveMeCurrentBreakPointName that can help me execute an action in a component like so: const currentBreakPointName = MaterialUIGiveMeCurrentBreakPointName() if(currentBreakPointName === 'myCustomBreakPointN ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Tips for printing several div elements with a set width and height without altering their size

At my workplace, we have perforated paper that employees fill out and cut to use as information cards. I am working on writing code using ASP.net core to input information onto these cards after a transaction. I have created a preview of the card in an HTM ...

Encrypting data between two Node.js servers

I am looking to create a Node.js daemon that can operate across multiple computers while facilitating message exchange between the daemons. Security is paramount, so I want to ensure the communication is encrypted. However, I am uncertain about which encry ...