【问题标题】:Ruby on Rails ganerate JsonRuby on Rails 生成 Json
【发布时间】:2018-05-26 22:38:40
【问题描述】:

我有一个生成 Json 的控制器。我使用该 Json 在 Google 地图中显示记录,但我只想显示那些具有参数 toll=="true" 的记录,而那些没有参数的将不会显示。

我正在考虑直接在 Json 中执行此过滤器(通过生成的 url),当我通过 javascript 调用它时,我使用我需要的参数调用 url。我如何才能通过 url 访问只有那些具有参数toll=="true" 的人?例如: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

谢谢。

【问题讨论】:

  • 这并不是在 Rails 中生成 JSON 的正确方法。您应该简单地执行类似msg = fares.as_json(include: ...) 的操作,其中include 是您想要的字段列表。你的整个控制器动作应该只有几行。 永远以这种方式手动构建包含 JSON 的字符串不是一个好主意,至少您应该构建一个 Ruby 哈希,然后调用 render json: my_hash 并让 Rails 为您生成有效的 JSON。跨度>

标签: javascript ruby-on-rails json


【解决方案1】:

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

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

正如它所说,只有 is_toll 为 true 的票价才会在 json 中呈现。

【讨论】:

  • 伙计,我不相信它这么简单,我也没有考虑过。非常感谢你。现在它正按我需要的方式工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 2013-04-18
  • 2011-08-02
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多