Rails 5:迭代条件以映射匹配记录

时间:2017-09-10 04:47:30

标签: ruby-on-rails ruby

我在rating/rating.rb模型中使用此方法,我基本上需要创建具有匹配inventoryrating ID的数组数组:

def inventory_ratings    
  inventory = Inventory::Inventory.where(id: inv).order(date: :desc)
  rating = Rating::Rating.where(id: rtg).order(valid_from: :desc)

  columns = [:inventory_id, :rating_id]
  values = inventory.map {|inv|
    if (inv.position_id == rating.position_id &&
        rating.valid_from..rating.valid_to.include?(inv.date))
      r = rating.id
    end
    [ inv.id, r ]
  }
  Rating::InventoryRating.import columns, values, validate: false
end

目前我收到此错误: NoMethodError: undefined method "position_id" for #<Rating::Rating::ActiveRecord_Relation:0x007ffff6067bf8>因为我可能不得不以某种方式遍历每个评分以获得position_idvalid_fromvalid_to

如何添加额外的迭代,以便每个inventory记录遍历每个评级记录并映射它是否与IF语句匹配,好吗?谢谢!

1 个答案:

答案 0 :(得分:1)

这个怎么样:

values = []
inventory.each do |inv|
  values.concat([inv.id].product(rating.where('position_id = ? AND valid_from <= ? AND valid_to >= ?', inv.position_id, inv.date, inv.date).ids))
end.uniq.compact