fetch data to React from Rails

问题内容:

On my Meals#index page, I want to display a map that renders all restaurants that are inside the displayed-map’s boundaries. (each meal belongs to a restaurant, the map is actually displayed along with a list of meals, like the AirBnB search page but with food instead of flats)

When I try to get data from rails to React, I get the following error:

missing keywords: 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

models/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

meals/index.html.erb

<%= react_component("App", prerender: false) %>

问题评论:

    
Can you add some stack trace?
    
the app trace is: 1 - app/models/restaurant.rb:24:in 'look_at' 2- app/controllers/meals_controller.rb:28:in 'index'
– Jules Corb
6 hours ago
1  
Check debugging the value of search_params.to_h.symbolize_keys.
1  
That was the problem. Once I get the right format for search_params, It does work. However it returns a whole JSON and does not render the view. I guess I can only use this technique using rails as an API. My rails app isn’t so I must find another way to render my map.
– Jules Corb
3 hours ago

原文地址:

https://stackoverflow.com/questions/47750155/fetch-data-to-react-from-rails

Add a Comment