Add new object to ActiveRecord :: Relation

I have objects in my database that the user can query, this of course gives an object ActiveRecord::Relation

.

Sometimes there are not enough places in the scope from which the user is searched, so I want to put it with the results Foursquare

from their API. Since these results are in a different format than in my places, I decided to convert them to my object Venue

and add them to the query result, but everything I try seems to fail. This is the relevant block of code:

@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

      

After that @venues

does not contain newly created objects Venue

. I also tried to use <<

to add it to Relation

, but that also didn't work. Any idea how I can do this? Different approaches to my problem are also welcomed.

+3


source to share


1 answer


Convert @venues

to array and add to array. @venues.build

will return a new object to you. but it won't be automatically added to the collection.



@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

      

+2


source







All Articles