2017-07-15 16 views
-1

模型Rails的顯示錶中的數據動態

class Smoothval < ActiveRecord::Base 

has_many :smoothings 
has_many :steps 

end 

class Step < ActiveRecord::Base 
belongs_to :usdzar 
belongs_to :smoothing 
belongs_to :smoothval 

default_scope lambda { 
    order(id: :desc) 
} 

end 

class Usdzar < ActiveRecord::Base 

has_many :smoothings 
has_many :steps 

end 

索引視圖,我想實現:

<table><thead> 
<tr> 
<th>Smoothing1</th> 
<th>Smoothing2</th> 
</tr></thead> 

<tbody> 
<tr> 
<td>"finalsmprice","stepnum"</td> 
<td>"finalsmprice","stepnum"</td> 
</tr> 
</tbody> 
</table 

因此,所有的fsmprices和stepnums從步驟表中的每個smoothval

我的index.html.erb看起來像這樣:

<h1>Listing Steps</h1> 
<table class="table table-striped table-bordered table-condensed"> 
<thead> 

<% Step.all.includes(:smoothval).group_by(&:smoothval_id).each do |smoothval_id, steps| %> 
<tr> 
<th> 
Smoothing: <%= smoothval_id %> 
</th> 
</tr> 
</thead> 

<tbody> 
<% steps.each do |step| %> 
<tr> 
<td> 
(<%= step.fsmprice %>): <%= step.stepnum %> 
    </td> 


    <% end %> 
</tr> </tbody> 
<% end %> 

</table> 

該表非常長,顯然將所有標題和數據相互顯示。我試圖創建一個postgres數據透視表,但是使用tablefunc失敗了,所以回到了試圖在rails中執行的操作。

在我的控制器中,我可以按照如下方式將數組的平滑度(表標題) 1,5]:

sv = Smoothval.where('id IN (SELECT DISTINCT(steps.smoothval_id) FROM steps)') 
@assigned = sv.pluck(:id)  

我怎樣才能得到上面的表格佈局

感謝

回答

0

這是太困難,就翻過一個貼子,說其最好創建一個數據透視表 無論其多數民衆贊成不那麼容易在Postgres中,tablefunc擴展的問題在於它不會動態分配列,所以需要靜態分配。所以我現在走了這條路線,並測試了功能https://github.com/hnsl/colpivot

我堅持基礎知識,並做到了這一點,但需要更多地考慮重構解決方案。

SELECT c_crosstab('Select * from steps', 'ct_view', 'id', 'smoothval_id', 'stepnum', 'first'); 

SELECT * 
FROM crosstab(
    'SELECT usdzar_id, smoothval_id, stepnum 
    FROM steps 
    ORDER BY 1,2 ASC') -- needs to be "ORDER BY 1,2" here 
AS ct ("SV" int, "Smooth1" int, "Smooth2" int, "Smooth3" int); 

希望這有助於somoene其他