Search code examples
javascriptruby-on-railsjsonfetchjbuilder

Jbuilder use POST request to API in Ruby On Rails


I try to divide Backend and Frontend in my project by using Rails and ReactJS.

And I have a function to do the async processing for POST request and using the gem Jbuilder to produce the JSON API

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 ) ) 
     })
})

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 I have _deal.json.jbuilder file in views/deals

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

I will get alert {id: number, shop_id: 1, deals_type: "workout", .....}

But I delete the _deal.json.jbuilder file, I will get {} null object.

why is the problem happening?


Solution

  • This line:

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

    Tells Rails to render your show view for JSON, which likely loads your app/views/deals/show.json.jbuilder view; that view itself likely just renders your _deal partial. Deleting the partial causes that view definition to become invalid.

    So, don't delete the partial unless you're also prepared to update the templates that refer to it.