Ruby-如何将项目从ActiveRecord添加到现有的哈希结构?

时间:2019-02-12 15:09:53

标签: ruby-on-rails ruby

我正在更新现有的Rails项目,并且该项目的菜单通过以下结构呈现:

def main_menu
    {
        users: item_hash('Users', @view.users_path),
        cars: item_hash('Cars', @view.cars_path),
        bikes: item_hash('Bikes', @view.bikes_path),
        other_group: item_group('Other', {
          fees: item_hash('Fees', @view.fees_path),
          penalties: item_hash('Penalties', @view.penalties_path),
          bonuses: item_hash('Bonuses', @view.bonuses_path)
        }),
        calendar: calendar_menu
    }
end

我需要在此结构中添加一个新项(将从DB中加载数据),所需的输出应如下所示(添加brands_group):

def main_menu
        {
            users: item_hash('Users', @view.users_path),
            brands_group: item_group('Brands', {
              Audi: item_hash('Audi', @view.edit_brand_path(1),
              BMW: item_hash('BMW', @view.edit_brand_path(2),
              Toyota: item_hash('Toyota', @view.edit_brand_path(3)
            }),
            cars: item_hash('Cars', @view.cars_path),
            bikes: item_hash('Bikes', @view.bikes_path),
            other_group: item_group('Other', {
              fees: item_hash('Fees', @view.fees_path),
              penalties: item_hash('Penalties', @view.penalties_path),
              bonuses: item_hash('Bonuses', @view.bonuses_path)
            }),
            calendar: calendar_menu
        }
    end

但是,如何从Brand模型中加载数据并将其放入这样的结构中?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

brands = Brand.all.map do |brand|
  [brand.name.to_sym, item_hash(brand.name, @view.edit_brand_path(brand.id))]
end.to_h #assuming you have a name column on the brands table

{
  users: item_hash('Users', @view.users_path),
  brands_group: item_group('Brands', brands),
  cars: item_hash('Cars', @view.cars_path),
  bikes: item_hash('Bikes', @view.bikes_path),
  other_group: item_group('Other', {
    fees: item_hash('Fees', @view.fees_path),
    penalties: item_hash('Penalties', @view.penalties_path),
    bonuses: item_hash('Bonuses', @view.bonuses_path)
  }),
  calendar: calendar_menu
}