【问题标题】:Replace transpose method?替换转置方法?
【发布时间】:2014-03-31 21:16:27
【问题描述】:

我有以下代码:

table([
          ["UnitID", "First Name", "NPS Score", "Comments"],
          *[invite_unitid_arr, invite_name_arr, nps_score_integers_final, comment_arr]
          .transpose.reject{ |x| x[3].empty? }
      ], :position => :center, :column_widths => {0 => 50, 1 => 60, 2 => 60, 3 => 40, 4 => 150}) do
  row(0).style :background_color => 'C0C0C0'
end

我在数组数组上调用transpose。我正在重构这段代码,现在我有一个模型对象数组:

array = Model.all

我如何重写上面的内容,说“循环遍历每个模型(Model1、Model2 等)并使用属性 unit_id、first_name、nps_score、comment 创建一行,如下所示:Model1[:unit_id],Model1[:first_name],Model1[:nps_score],Model1[:comment]

【问题讨论】:

    标签: ruby-on-rails ruby arrays prawn transpose


    【解决方案1】:

    如果我理解正确,你有一个这样的对象数组:

    my_models = [ <MyModel id: 1, unit_id: 123, first_name: "Xxx", nps_score: 100, ...>,
                  <MyModel id: 2, unit_id: 456, first_name: "Yyy", nps_score: 200, ...>,
                  ...
                ]
    

    你想要一个这样的数组:

    [ [ "UnitID", "First Name", "NPS Score", "Comments" ],
      [ 123,      "Xxx",        100,         "..."      ],
      [ 456,      "Yyy",        200,         "..."      ],
      ...
    ]
    

    您真正需要做的就是:

    headers = [ "UnitID", "First Name", "NPS Score", "Comments" ]
    
    data = my_models.map do |model|
      [ model.unit_id, model.first_name, model.nps_score, model.comments ]
    end
    
    rows = [ headers, *data ]
    

    或者……

    data = my_models.map do |model|
             model.attributes.values_at(:unit_id, :first_name, :nps_score, :comments)
           end
    

    (无论哪种方式,您都可以将其设为单行,但请注意代码的可读性。)

    当然,最好只选择您要使用的列,这样您就可以这样做(添加您需要的任何whereorder 等调用):

    my_models = MyModel.select([ :unit_id, :first_name, :nps_score, :comments ]).where(...)
    data = my_models.map(&:attributes)
    # => [ [ 123, "Xxx", 100, "..." ],
    #      [ 456, "Yyy", 200, "..." ],
    #      ...
    #    ]
    

    在 Rails 4 中,pluck 方法接受多个参数,这让这变得更加容易:

    data = MyModel.where(...).pluck(:unit_id, :first_name, :nps_score, :comments)
    # => [ [ 123, "Xxx", 100, "..." ],
    #      [ 456, "Yyy", 200, "..." ],
    #      ...
    #    ]
    

    【讨论】:

      【解决方案2】:

      我不完全确定你想在这里实现什么,但似乎你正在寻找pluck 方法。由于 rails 4 它允许您一次采摘多列(默认情况下会采摘所有列)。所以看来:

      Model.pluck(:unit_id, :first_name, :nps_score, :comment)
      

      这是您正在寻找的 - 实际上要好得多,因为它不实例化新对象并且只对 db.js 进行一次调用。 .它将返回二维数组,每个模型一行。如果您更喜欢同一列的不同值,请在上面添加转置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 2011-03-15
        • 2016-08-18
        • 1970-01-01
        • 1970-01-01
        • 2012-04-10
        • 2015-11-29
        相关资源
        最近更新 更多