0
我想創建一個幫助器方法來幹掉我的視圖很多,這本質上會爲我呈現出一張表。我期待用至今的語法是:Rails 3.1表助手
= table_for @notes do
= column "Date" do
= time_ago(note.created_at)
= column "Content" do
= note.content
這是我至今助手:
module TableHelper
def table_for(items)
@resource = items.singularize # Singularizes the resource
@columns = []
yield
# Create a table
content_tag :table, class: 'table table-striped' do
thead + tbody(items)
end
end
def thead # Loop through columns and print column label
content_tag :thead do
content_tag :tr do
@columns.each do |c|
concat(content_tag(:th, c[:label]))
end
end
end
end
def tbody(items) # This bit fails :(
content_tag :tbody do
items.each { |e|
concat(content_tag(:tr){
@columns.each { |c|
e[c[:label]] = c[:block].call(e[c[:label]]) if c[:block]
concat(content_tag(:td, e[c[:block]]))
}
})
}
end
end
def column (label, &block) # Takes a label and block, appending it to the columns instance
@columns << { label: label, block: block}
nil # Stops it printing the @columns variable
end
end
如果這個不足之處在於在TBODY方法。我不知道如何將單一資源傳遞給該塊。
例如在這種情況下,我將@notes作爲集合傳入。 在列塊中,我然後調用note.created_at。 但是,'note'沒有被定義。
任何幫助將不勝感激!
我不理解'table_for'方法線'@resource = items.singularize'。你不是在'Array'上調用'singularize'方法。我想這應該不起作用。請多解釋一下? – Samiron
你絕對正確,這並不意味着在那裏!這是來自以前的嘗試,但如果您對如何使這項工作非常棒的建議有任何建議! :) – Ammar
您是否嘗試修改某些內容,而不是您在問題中發佈的內容。如果是的話,請更新你的問題,否則我更新了我的答案,你可以嘗試一個鏈接。除此之外,我會在週末看看這個。 – Samiron