在我的Meals#index页面上,我想显示一个地图,该地图呈现显示地图边界内的所有餐馆。 (每餐都属于一家餐馆,地图实际上会与一份餐点一起显示,例如AirBnB搜索页面,但是用食物代替公寓)
当我尝试从rails获取数据到React时,我收到以下错误:
缺少关键字:min_lat,max_lat,min_lng,max_lng
Map.js
fetchPlacesFromApi() {
this.setState({ places: [] })
fetch(`/meals?min_lng=${this.xMapBounds.min}&max_lng=${this.xMapBounds.max}&min_lat=${this.yMapBounds.min}&max_lat=${this.yMapBounds.max}`,
{ method: 'GET' })
.then((response) => response.json())
.then((response) => this.setState({ places: response }))
}
meals_controller.rb
class MealsController < ApplicationController
def index
@restaurants = Restaurant.where(id: @meals.pluck(:restaurant_id))
places = @restaurants.look_at(search_params.to_h.symbolize_keys)
render json: places
end
private
def search_params
params.permit(:min_lng, :max_lng, :min_lat, :max_lat)
end
end
模型/ restaurant.rb
scope :by_longitude, -> (min, max) { min && max ? where('longitude >= :min AND longitude <= :max', min: min, max: max) : all }
scope :by_latitude, -> (min, max) { min && max ? where('latitude >= :min AND latitude <= :max', min: min, max: max) : all }
API_RESULTS_LIMIT = 100
def self.look_at(min_lat:, max_lat:, min_lng:, max_lng:)
by_latitude(min_lat, max_lat).
by_longitude(min_lng, max_lng).
limit(API_RESULTS_LIMIT)
end
饭菜/ index.html.erb
<%= react_component("App", prerender: false) %>