2012-09-04 122 views
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'沒有被定義。

任何幫助將不勝感激!

+0

我不理解'table_for'方法線'@resource = items.singularize'。你不是在'Array'上調用'singularize'方法。我想這應該不起作用。請多解釋一下? – Samiron

+0

你絕對正確,這並不意味着在那裏!這是來自以前的嘗試,但如果您對如何使這項工作非常棒的建議有任何建議! :) – Ammar

+0

您是否嘗試修改某些內容,而不是您在問題中發佈的內容。如果是的話,請更新你的問題,否則我更新了我的答案,你可以嘗試一個鏈接。除此之外,我會在週末看看這個。 – Samiron

回答

0

也許你需要

= table_for @notes do |note| 

table_for功能,以取代

= table_for @notes do` 

,當你得到你應該做yield item。這裏itemitems陣列的一個實例。所以還需要準備。

編輯:該鏈路具有不同的方法:https://stackoverflow.com/a/11483295/1160106