【发布时间】: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