【问题标题】:ActiveRecord Relation: append objects inside the ActiveRecord::Relation ObjectActiveRecord Relation:在 ActiveRecord::Relation 对象中附加对象
【发布时间】:2016-03-07 21:13:50
【问题描述】:

我有以下型号:

#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)

【问题讨论】:

  • 您能否放置一个调试器或绑定并验证 Location.partner_locations 和 Location.education_locations 的输出?你也可以为locations = Location.none发布其余代码(如父方法)如果为真.....
  • .none 似乎确保不会返回任何内容。您可以使用不同的基本范围,并且仅在没有其他条件匹配时才追加。

标签: ruby-on-rails ruby activerecord


【解决方案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)

【讨论】:

    【解决方案2】:

    尝试以下方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2014-03-08
      相关资源
      最近更新 更多