将新对象添加到 ActiveRecord::Relation



我的数据库中有用户可以查询的场所,这当然会产生一个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

最新更新