[英]How do I display data in a Ruby on Rails site in left and right columns of HTML table?
[英]Display data in columns not rows using Ruby on Rails
我想在我的網頁中以“列”而不是“行”顯示數據。
使用Ruby on Rails最有效的方法是什么?
非常感謝您的幫助!
一種簡單的解決方案是使用數組“旋轉”信息。 像這樣的(偽)代碼(無法檢查atm)
控制器代碼:
@stuffs = Stuff.find(:all)
@rotated = []
@rotated[0] = [] # Stuff column0
@rotated[1] = [] # Stuff column1
# etc
index = 0
# Now put the stuff in an array for easy(ier) access
@stuffs.each do |stuff|
@rotated[0][index] = stuff.detail0
@rotated[1][index] = stuff.detail1
index += 1
end
在您的視圖中,您將需要以下內容:
<table>
Table head here!
<% 2.times do |row| %> # Build table (we have 2 stuff details, hence the 2 here)
<tr>
<% index.times do |column| %>
<td><%= @rotated[row][column] %></td>
<% end %>
</tr>
<% end %>
<table>
當然,有更好的解決方案,但這對我來說似乎是最簡單/一般的。 旋轉某些模型中的某些數據。
就像其他人說的那樣,有更多信息,我們可能會更好地幫助您!
這是我的解決方案。 它需要一個數組,例如["a", "b", "c", "d"]
並將其轉換為以下數組: [["a", "b"], ["c"], ["d"]]
,因此易於使用以列顯示數據。
def categories_in_columns(categories, number_of_groups=3)
groups = []
elements_per_column = categories.size / number_of_groups
extra_elements = categories.size % number_of_groups
has_extra_elements = (extra_elements > 0 ? 1 : 0)
0.upto(number_of_groups-1).each do |i|
groups[i] = []
while groups[i].size < (elements_per_column + has_extra_elements)
groups[i] << categories.shift
extra_elements -= 1 if groups[i].size > elements_per_column
end
has_extra_elements = 0 if extra_elements == 0
groups[i].compact!
end
groups.delete_if { |i| i.empty? }
end
和它的規格:
it "arranges categories into columns" do
categories_in_columns(["a", "b", "c", "d", "e"]).should == [["a", "b"], ["c", "d"], ["e"]]
categories_in_columns(["a", "b", "c", "d"] ).should == [["a", "b"], ["c"], ["d"]]
categories_in_columns(["a", "b", "c"] ).should == [["a"], ["b"], ["c"]]
categories_in_columns(["a", "b"] ).should == [["a"], ["b"]]
categories_in_columns(["a"] ).should == [["a"]]
end
改編自先前的類似問題/答案 :
def rotate(matrix)
columns = matrix.first.size
rows = matrix.size
result = []
columns.times { |y|
result[y] = []
rows.times { |x|
result[y][x] = matrix[x][y]
}
}
result
end
我相信這可以稱為“換位”,因為您實際上只是想將第1行變成第1列,以此類推,而不是旋轉數組。 也就是說,如果您逆時針旋轉四分之一轉,則array[0][0]
將在左下角顯示。 上面的實現假設您仍然希望[0] [0]保留在左上方:
1 2 3 4
5 6 7 8
9 0 a b
1 5 9
2 6 0
3 7 a
4 8 b
我還假設所有行都具有相同數量的元素/列。
哦,嘿,你不知道嗎: Array#transpose ...
<%= render :partial => 'mytable', :collection => @array.transpose %> # untested
如果要從數據庫中提取數據,則應考慮使用PIVOT運算符(至少在SQL Server中-我不確定SQLLite或MySQL)。 這樣,您仍然可以使用“常規” UI方法,並且仍以列而不是行顯示數據。 只是一個想法...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.