将父id传递给hash选项的选项

时间:2014-07-25 09:45:47

标签: ruby-on-rails ruby forms hash

我有一个方法,它从DELIVERYCOST数据库中获取两列,并在分组'title'下对列'timing'进行分组。它将其变为哈希

  def self.titles_by_timing
    self.pluck(:id, :timing, :title).group_by(&:first).each { |_, v| v.map!(&:last) }
  end

DeliveryCost.titles_by_timing
=> {"Install"=>["Luton Day (7am - 7pm)", "LWB Day (7am - 7pm)", "Luton Overtime (7pm - 7am)", "LWB Overtime", "Helper Day (7am - 7pm)", "Helper Overtime"], "Breakdown"=>["Luton Day (7am - 7pm)", "LWB Overtime", "Luton Overtime (7pm - 7am)", "Helper Day (7am - 7pm)", "Helper Overtime"], "Fuel"=>["Congestion Charge", "Fuel in London Zone 1-2", "Fuel in London Zone 3-4", "Fuel By Milege (Out of M25)]}

这是JOB DELIVERY COSTS

表单中的部分
= f.select :delivery_cost_id, option_groups_from_collection_for_select(DeliveryCost.titles_by_timing, :timing, :title, :id) 

由于JOB DELIVERY COSTS属于交付成本,并且交付成本有许多作业交付成本,我需要传递id以便在创建作业交付成本实例时创建关联。但是我这样做很困难。我该怎么做,我是否扩展了我目前的方法?

非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

似乎DeliveryCost.titles_by_timing已经在做所有繁重的工作,所以你应该使用grouped_options_for_select代替option_groups_from_collection_for_select

检查ActionView::Helpers::FormOptionsHelper#grouped_options_for_select

<强>更新

尝试将以下内容与grouped_options_for_select

一起使用
def self.titles_by_timing
  self.all.each_with_object(Hash.new([])) do |delivery_cost, grouped|
    grouped[delivery_cost.title] |= [[delivery_cost.id, delivery_cost.timing]]
  end
end

请注意,由于将所有对象加载到内存中,此方法可能表现不佳。如果这是一个问题,您可以尝试一些缓存,memoization或将昂贵的查询委托给数据库。