代码之家  ›  专栏  ›  技术社区  ›  Felipe Marcon

Ruby on Rails Ganerate JSON公司

  •  0
  • Felipe Marcon  · 技术社区  · 7 年前

    我有一个生成JSON的控制器。我使用JSON在谷歌地图中显示记录,但我只显示那些有参数的记录。 toll=="true" 以及那些没有的,将不会显示出来。

    我正在考虑直接在JSON中执行这个过滤器(通过生成的URL),当我通过JavaScript调用这个过滤器时,我用我需要的参数调用这个URL。我怎样才能通过URL访问只有那些有参数的 toll==“真” ?例子: localhost:3000/map_pis?tool=="true" ?:

    class PointOfInterestsController < ApplicationController
      def map
        pis = PointOfInterest.all
        fares = FareCity.all
        msg = '
          {
            "pis": [
              '
        total_pis = ''
        pis.each do |p|
          total_pis += '
         {"kilometer": ' + p.kilometer.to_s + ',
          "category": "pis",
          "name": "' + p.name + '",
          "show_on_map": "' + p.point_of_interest_category.show_on_map.to_s + '",
          "lat": ' + p.lat.to_s + ',
          "lng": ' + p.lng.to_s + ',
          "icon": "' + p.point_of_interest_category.icon.url + '",
          "description": "' + p.description + '",
          "image": "' + p.image.url + '"},'
        end
    
        fares.each do |f|
          total_pis += '
         {"kilometer": ' + f.kilometer.to_s + ',
          "category": "fare",
          "name": "' + f.name + '",
          "toll": "' + f.is_toll.to_s + '",
          "lat": ' + f.lat.to_s + ',
          "lng": ' + f.lng.to_s + ',
          "icon": "/img/icon_fare_map.png",
            "pedagios": ['
        total_fares = ''
    
        f.fare_pricings.each do |fp|
          total_fares += '
          {"title": "' + fp.fare_category.title.to_s + '",
          "price": ' + fp.price.to_s + '},'
        end
    
        total_pis += total_fares[0...-1]
    
        total_pis += '] },'
        end
    
        msg += total_pis[0...-1]
    
        msg +='
            ]
          }
        '
        render :json => msg
      end
    end
    

    谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sovalina    7 年前

    假设你所说的 toll=="true" 指属性 is_toll (对/错)的 FareCity 模型,您可以直接在控制器内部进行条件显示:

    def map
      pis = PointOfInterest.all
      fares = FareCity.where(is_toll: true)
      #...
    end
    

    正如上面所说,只有在 收费吗? 如果为true,则将在JSON中呈现。