我的数据库中有用户可以查询的场所,这当然会产生一个ActiveRecord::Relation
对象。
有时用户搜索的区域没有足够的场地,所以我想用他们的 API Foursquare
结果来填充它。由于这些结果的格式与我的场地不同,我决定将它们转换为我的Venue
对象并将它们添加到查询结果中,但无论我尝试什么,似乎都失败了。这是相关的代码块:
@venues = @venues.limit(30)
if @venues.count(:all) < 30
foursquare_client = foursquare_client()
fq_venues = foursquare_client.explore_venues(ll: params[:ll], radius: 1000, limit: 30 - @venues.count(:all), section: 'food')
for item in fq_venues.groups[0].items
fq_venue = item.venue
location = Location.build_from_foursquare(fq_venue)
@venues.build(name: fq_venue.name, foursquare_id: fq_venue.id, location: location)
end
end
在此之后@venues
不包含新创建的Venue
对象。我也尝试使用<<
将其添加到Relation
但这也不起作用。知道我该如何管理吗?也欢迎对我的问题采取不同的方法。
将@venues
转换为数组并添加到数组。 @venues.build
将返回一个新对象。但它不会自动添加到集合中。
@venues = @venues.limit(30)
if @venues.all.count < 30 #this converts @venues to array
foursquare_client = foursquare_client()
fq_venues = foursquare_client.explore_venues(ll: params[:ll], radius: 1000, limit: 30 - @venues.count(:all), section: 'food')
for item in fq_venues.groups[0].items
fq_venue = item.venue
location = Location.build_from_foursquare(fq_venue)
@venues << @venues.build(name: fq_venue.name, foursquare_id: fq_venue.id, location: location)
end
end