【问题标题】:How to merge hash with activerecord relations in controller / scope如何在控制器/范围内将散列与活动记录关系合并
【发布时间】:2017-06-29 06:59:04
【问题描述】:
  • 我有 Item 模型(表),列 [id,name,notes]。然后我有哈希让我们用列 [id_of_item,total_stock] 将其称为 stock

  • 当我在控制器中进行查询时,我想将哈希作为附加列加入表中,以便显示项目的 total_stock。

  • 我不喜欢使用 map/each (循环遍历所有项目,因为 items 表有数千条记录。我仍然不知道这是否可能,谢谢。

【问题讨论】:

    标签: ruby-on-rails activerecord hash


    【解决方案1】:

    如果您的股票是
    [[1, "total_stock_1"], [2, "total_stock_2"]]
    你应该使用
    stock = Hash[[[1, "total_stock_1"], [2, "total_stock_2"]]]
    将您的 hash 翻译成这种风格
    stock = {1 => "total_stock_1", 2 => "total_stock_2"}

    stock = {1 => "total_stock_1", 2 => "total_stock_2"}
    @items = Item.all.map{|item| item.attributes.merge({total_stock: stock[item.id]})}
    # the output will be a json not a ActiveRecordRelation
    [
      {:id => 1, :name => 'item1', :notes => xxx, :total_stock => "total_stock_1"},
      {:id => 2, :name => 'item2', :notes => yyy, :total_stock => "total_stock_2"}
    ]
    

    【讨论】:

    • 谢谢,作为我上面问题的信息,我已经定义了哈希的键和值,库存哈希键是 the_id_of_the_item 并且值是项目的总库存
    【解决方案2】:

    您可以在控制器中执行此操作:

     @items = Item.all
     render json: @items.map{|item| {'item': item.as_json.merge stock.select{|item| item['id_of_item'] == item.id}['total_stock']} }}
    

    【讨论】:

    • 谢谢,如果只是一个项目记录(显示)我没有问题,我上面问的是索引控制器,将项目的内容与哈希的内容合并。
    • 更改了索引操作的答案。
    猜你喜欢
    • 2011-10-06
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    相关资源
    最近更新 更多