我有一個控制器,它使用來自模型的資料呈現 json。當我輸入路線以獲取它時,它什么也不做,只是在控制臺中顯示和錯誤。
控制器:
class Api::ForecastController < ApplicationController
before_action :set_hourly_forecast, only: %i[ show edit update destroy ]
def index
respond_to do |format|
format.html do
@hourly_forecasts = HourlyForecast.where(forecast_location_id: params[:forecast_location_id]).paginate(:page => params[:page], :per_page=>24) if params[:forecast_location_id].present?
end
format.json do
weather_service = WeatherService.where(name: params[:name])
@forecast_location = ForecastLocation.where(weather_service_id: weather_service)#& municipality: @municipality.name)
@hourly_forecasts = HourlyForecast.where(forecast_location_id: forecast_location.id ).paginate(:page => params[:page], :per_page=>24) if params[:forecast_location_id].present?
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_hourly_forecast
@hourly_forecast = HourlyForecast.find(params[:id])
end
# Only allow a list of trusted parameters through.
def hourly_forecast_params
params.require(:hourly_forecast).permit(:forecast_location_id, :date, :temperature, :humidity, :rain, :rain_probability, :wind_speed, :wind_direction)
end
end
錯誤:
> Started GET "/api/forecast.json?name=dark_sky" for 127.0.0.1 at 2022-04-20 18:33:29 0200
Processing by Api::ForecastController#index as JSON
Parameters: {"name"=>"dark_sky"}
No template found for Api::ForecastController#index, rendering head :no_content
Completed 204 No Content in 53ms (ActiveRecord: 6.2ms | Allocations: 4983)
我使用的路線
127.0.0.1:3000/api/forecast.json?name=dark_sky
所以輸出應該是一個包含所有小時模型的 json。但它什么也不做,在控制臺上它確實得到了選擇,但跳過了模板的這個錯誤,我不明白,因為我是新來的。
如果需要更多控制器、模型或任何內容,請在評論中提問。
uj5u.com熱心網友回復:
例如,您必須有一個單獨的模板檔案來呈現 json index.json.jbuilder。
# app/views/api/forecasts/index.json.jbuilder
json.array! @hourly_forecasts do |hourly_forecast|
json.extract! hourly_forecast, :id, :forecast_location_id, :date, :temperature, :humidity, :rain, :rain_probability, :wind_speed, :wind_direction
json.url api_forecast_url(hourly_forecast, format: :json)
end
https://github.com/rails/jbuilder
如果不需要過多自定義渲染的json,可以在controller中行內渲染json
format.json do
weather_service = WeatherService.where(name: params[:name])
@forecast_location = ForecastLocation.where(weather_service_id: weather_service)#& municipality: @municipality.name)
@hourly_forecasts = HourlyForecast.where(forecast_location_id: forecast_location.id ).paginate(:page => params[:page], :per_page=>24) if params[:forecast_location_id].present?
render json: @hourly_forecasts
end
https://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json
https://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460238.html
上一篇:在ActiveRecord::Relationdelete_by方法上不呼叫after_commit和after_destroy回呼
