1
votes

I have the following model:

#models/location.rb
class Location < ActiveRecord::Base
    scope :partner_locations, ->{where(partner: true)}
    scope :education_locations, ->{where(education: true)}
end

Then I have the following code:

locations = Location.none
if true
  #append onto that locations activerecord::relation object those locations that are partner locations
  locations << Location.partner_locations
end
if true
  #append onto that locations activerecord::relation object those locations that are education locations
  locations << Location.education_locations
end
return locations

I would think that this code would return an activerecord::relation object with some objects inside of it. Instead it just returns: [], just an empty Location::ActiveRecord_Relation object.

How do I append records onto this Location::ActiveRecord_Relation object?

I did some research and I see some people suggest using merge but I don't think that is what I want. I am not doing any filtering. I only want to append on Location objects inside that Location::ActiveRecord_Relation object so that I can then use other methods on it like: locations.order(:name).

2
Can you place a debugger or binding and verify what the output of Location.partner_locations and Location.education_locations? Also can you post the rest of the code(like the parent method) for locations = Location.none if true ..... - ruby_newbie
.none seems to ensure that nothing gets returned. You might use a different base scope, and only append none if no other condition is matched. - Thomas Klemm

2 Answers

1
votes

If someone has a better way of doing this I would love to know.

I got it to do what I wanted to do by appending to a regular array, and then before returning it, I transformed it into an activerecord::relation so that I could use activerecord methods on it. It would be nice If I could do the whole thing with the same activerecord::object:

locations = []
if true
  #append onto that locations array all the location objects that are partner locations
  locations = locations + Location.partner_locations
end
if true
  #append onto that locations array all those location objects those locations that are education locations
  locations = locations + Location.education_locations
end
return Location.where(id: locations.map(&:id)).order(:name)
0
votes

Try the following:

@locations = Location.order(:name)
@locations = @locations.partner_locations if # what ever logic 
@locations = @locations. education_locations if # what ever logic 
@locations