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?