我不熟悉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()
我很确定第二行不是最好的方法,但我无法弄清楚如何改变它。
答案 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