2017-08-24 137 views
0

我尝试使用Rails和ReactJS在我的项目中划分后端和前端。Jbuilder在Ruby On Rails中使用POST请求API

而且我有一个函数来做到异步处理POST请求和使用宝石Jbuilder 产生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)) 
    }) 
}) 

控制器:

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 

如果我有_deal.json.jbuilder档案views/deals

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

我会得到警报{id: number, shop_id: 1, deals_type: "workout", .....}

但我删除_deal.json.jbuilder文件,我会得到{}空对象。

为什么问题在发生?

回答

1

这条线:

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

告诉Rails渲染你show视图JSON,这可能加载您app/views/deals/show.json.jbuilder图。该视图本身可能只是呈现您的_deal部分。删除部分原因导致视图定义变为无效。

因此,除非您还准备更新引用它的模板,否则不要删除该部分。