简体   繁体   English

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

[英]Ruby - how to add items from ActiveRecord to an existing hash structure?

I am updating an existing Rails project and the menu of the project is rendered through the following structure: 我正在更新现有的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

I need to add a new item to this structure (data would be loaded from DB) and the desired output would look like this (added brands_group ): 我需要向该结构添加一个新项目(数据将从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

However, how do I load the data from the Brand model and put them to such a structure? 但是,如何从Brand模型中加载数据并将其置于这样的结构中?

You could do something like: 您可以执行以下操作:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM