Ruby on rails ActiveRecord关系:在ActiveRecord::Relation对象内追加对象
我有以下型号:Ruby on rails ActiveRecord关系:在ActiveRecord::Relation对象内追加对象,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有以下型号: #models/location.rb class Location < ActiveRecord::Base scope :partner_locations, ->{where(partner: true)} scope :education_locations, ->{where(education: true)} end #models/location.rb 类位置{where(合作伙伴:true)} 经营范围:教育地点,->{whe
#models/location.rb
class Location < ActiveRecord::Base
scope :partner_locations, ->{where(partner: true)}
scope :education_locations, ->{where(education: true)}
end
#models/location.rb
类位置{where(合作伙伴:true)}
经营范围:教育地点,->{where(教育:true)}
结束
然后我有以下代码:
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
locations=Location.none
如果是真的
#将作为合作伙伴位置的位置附加到该位置activerecord::relation对象
位置如果有人有更好的方法,我很想知道
我通过将它附加到一个常规数组来完成我想做的事情,然后在返回它之前,我将它转换成一个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)
请尝试以下操作:
@locations = Location.order(:name)
@locations = @locations.partner_locations if # what ever logic
@locations = @locations. education_locations if # what ever logic
@locations
您能否放置调试器或绑定并验证Location.partner\u locations和Location.education\u locations的输出内容?您还可以发布locations=Location.none的其余代码(如父方法),如果为true。。。。。似乎可以确保什么都不会被退回。您可以使用不同的基本作用域,并且只有在没有其他条件匹配的情况下才附加none。