gpt4 book ai didi

ruby-on-rails - Rails API 不拆分 Json

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:19 24 4
gpt4 key购买 nike

奇怪的问题。如果底部的类是一个模块,拆分 Json 没有问题,如果它只是方法,也可以,但问题是..当它是一个类时,它不再拆分 Json,并返回一个空数组.. 但是,如果是一个类,我会做一个 puts 对象,它实际上是 puts it..关于为什么的任何想法?我该如何解决?

我有这个 Controller :

 def index
begin
call_employee_work_locations_api
rescue => ex
render :json => {"service unavailable": "0001" }, :status => :service_unavailable
end
end

我有这个服务:

def call_employee_work_locations_api
auth = {:username=>ENV["USERNAME"], :password=>ENV["PASSWORD"]}
employee_locations = HTTParty.get(employee_work_Location_url , :basic_auth => auth)
#serialize_work_location(employee_locations)
serializer = EmployeeSerializer.new
serializer.serialize_work_location(employee_locations)
end

我有这个构建器:

json.array!(@top_locations) do |location|
json.extract! location, :name, :description, :latitude, :longitude
end

我有这门课:

class EmployeeSerializer

def serialize_work_location(employee_locations)
employee_locations= JSON.parse(employee_locations)
locations=[]

employee_locations["work_locations"].each do |attributes|
location = Location.new(attributes["latitude"],attributes["longitude"],attributes["description"],attributes["name"])
locations.push(location)
end
employee_locations_selector(locations)
end

def top_office_location_selector(locations, city)
top_locations=[]
locations.each do |office|
if office.name == city[0] then top_locations.push(office) end
if office.name == city[1] then top_locations.push(office) end
end
@top_locations = top_locations
p @top_locations <--- it prints the object perfectly, but does not pass to the view, I get an empty array instead.
end

def employee_locations_selector(locations)
city = locations.each_with_object(Hash.new(0)) { |locations, counts| counts[locations.name] += 1 }.max_by{|k,v| v}
top_office_location_selector(locations, city)
end
end

最佳答案

实例变量 @top_locations 被设置在 EmployeeSerializer 类的范围内,而不是您的 Controller 。因此它只是一个普通的实例变量,所以 Rails 对此一无所知。您可以将 #top_office_location_selector 的返回值分配给 Controller 中的实例变量,它应该可以工作。

附带说明一下,通过使用 #map 而不是 #each 可以大大简化代码。

关于ruby-on-rails - Rails API 不拆分 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37510592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com