2014-11-20 92 views
3

我在我的数据库中有一个用户可以查询的场所,这当然会产生一个ActiveRecord::Relation对象。将新对象添加到ActiveRecord ::关系

有时在用户搜索的区域没有足够的场地,所以我想用他们的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,但也没有奏效。任何想法如何我可以管理这个?对我的问题采取不同的方法也是受欢迎的

回答

2

@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 
+0

非常感谢。现在我没有得到的是,在我做了@venues << Venue.new之前......并没有奏效,但是当它是同样的事情时,这种感觉不知如何。 – 8vius 2014-11-20 18:57:31

+0

它不是一回事。之前它是一个'ActiveRelation'对象。现在它是一个'数组'。我认为它会尝试在ActiveRelation对象上使用'<<'时将对象保存在数据库中 – usha 2014-11-20 18:59:44

+0

不,不需要,并且该行转换为数组不是必需的,只需要@venues << @venues .build'。我不需要它作为数组,因为在此之后可能会发生其他级联查询。 – 8vius 2014-11-20 19:04:43

相关问题