在一行中优化多个Active Record查询

时间:2014-07-31 18:15:52

标签: ruby-on-rails activerecord

我不熟悉Ruby并试图弄清楚如何最好地使用ActiveRecord。目前,我遇到一个问题,我从一个对象获取一个ID,然后想要使用该ID搜索另一个对象并获取它的值并将它们映射到一个新对象,如下所示:

Obj_features = {}
ObjFeature.where(obj_id: @obj.id).map{|ft| obj_features[ft.feature_id] = Feature.where(id: ft.feature_id).select('id, title, icon')}
@features = obj_features.values()

我很确定第二行不是最好的方法,但我无法弄清楚如何改变它。

1 个答案:

答案 0 :(得分:2)

你需要这样的东西吗?

class Feature < ActiveRecord::Base
  belongs_to :object_feature
end

class ObjectFeature < ActiveRecord::Base
  has_many :features
end


obj_feature.find(objid).feature = feature.find(feature_id)

您还应该看一下导轨Query Interface