我有以下型号:
#models/location.rb
class Location < ActiveRecord::Base
scope :partner_locations, ->{where(partner: true)}
scope :education_locations, ->{where(education: true)}
end
然后我有以下代码:
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
我认为这段代码会返回一个activerecord :: relation对象,里面有一些对象。相反,它只返回:[]
,只是一个空的Location :: ActiveRecord_Relation对象。
如何将记录追加到此Location :: ActiveRecord_Relation对象?
我做了一些研究,我看到有些人建议使用merge
,但我认为这不是我想要的。我没有做任何过滤。我只想在Location :: ActiveRecord_Relation对象中附加Location
个对象,以便我可以使用其他方法,如:locations.order(:name)
。
答案 0 :(得分:1)
如果有人有更好的方法,我很想知道。
我通过附加到常规数组来做我想要做的事情,然后在返回之前,我将其转换为activerecord :: relation,以便我可以在其上使用activerecord方法。如果我可以使用相同的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)
答案 1 :(得分:0)
尝试以下方法:
@locations = Location.order(:name)
@locations = @locations.partner_locations if # what ever logic
@locations = @locations. education_locations if # what ever logic
@locations