2012-09-04 79 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