2016-03-07 167 views
1

我有以下型號:ActiveRecord的關係:追加的ActiveRecord ::關係客體中的對象

#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

可將一個調試器或綁定,並驗證位置的輸出是什麼.partner_locations和Location.education_locations?你也可以發佈剩餘的代碼(如父方法)的位置= Location.none 如果屬實..... –

+0

['.none'](http://api.rubyonrails.org/classes/ActiveRecord /QueryMethods.html#method-i-none)似乎確保不會返回任何內容。您可能會使用不同的基本範圍,並且只有在沒有其他條件匹配的情況下才會附加none。 –

回答

1

如果有人有更好的方式做到這一點,我很想知道。

我通過附加到常規數組來完成我想做的事情,然後在返回之前將其轉換爲activerecord :: relation,以便我可以使用activerecord方法。這將是很好,如果我可以做這件事具有相同的ActiveRecord ::對象:

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

嘗試以下操作:

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