0

ビューを大量に乾燥させるためのヘルパー メソッドを作成しようとしています。これにより、基本的にテーブルがレンダリングされます。これまでに使用しようとしている構文は次のとおりです。

 = 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' は定義されていません。

どんな助けでも大歓迎です!

4

1 に答える 1

0

おそらくあなたは交換する必要があります

= table_for @notes do` 

= table_for @notes do |note|

table_forあなたが譲歩しているときの関数からあなたはするべきですyield item。これが配列itemの1つのインスタンスです。itemsだからそれも準備する必要があります。

編集:このリンクには別のアプローチがあります:https ://stackoverflow.com/a/11483295/1160106

于 2012-09-04T10:01:12.587 に答える