2014-03-31 96 views
-1

我有以下代碼:替換轉置方法?

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 

我怎樣才能把上面的,說:「循環每一個模型(模型1,模型2等),並創建與屬性的行unit_id,first_name,nps_score,評論如下:Model1[:unit_id],Model1[:first_name],Model1[:nps_score],Model1[:comment]

回答

0

如果我理解正確的話,你有對象的一個​​這樣的數組:

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, "..." ], 
#  ... 
# ] 
0

我不完全確定你想在這裏實現什麼,但似乎你正在尋找pluck方法。由於導軌4,它允許您一次拔出多個列(默認情況下會拔取所有列)。如此看來,:

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

是你在找什麼 - 實際上是因爲它不實例化新對象要好得多,使得只需一個電話爲DB。 。它將返回2d數組,每個模型一行。如果您更喜歡同一列有不同的值,請在上面添加轉置。