【问题标题】:Rails 3.1 Table HelperRails 3.1 表格助手
【发布时间】:2012-09-04 09:19:39
【问题描述】:

我正在尝试创建一个辅助方法来大量干燥我的视图,这实际上会为我呈现一个表格。到目前为止,我希望使用的语法是:

 = 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' 没有定义。

任何帮助将不胜感激!

【问题讨论】:

  • 我不明白@resource = items.singularize 方法中的@resource = items.singularize 行。你不是在Array 上调用singularize 方法吗?我猜它不应该工作。请再解释一下?
  • 你的绝对正确,这不应该在那里!那是以前的尝试,但是如果您对如何使这项工作有任何建议,那就太好了! :)
  • 您是否正在尝试一些修改过的内容,而不是您在问题中发布的内容。如果是,请更新您的问题,否则我用您可以尝试的链接更新我的答案。除此之外,我会在周末看看这个。

标签: ruby-on-rails-3 helper


【解决方案1】:

可能需要更换

= table_for @notes do` 

通过

= table_for @notes do |note|

table_for 函数中,当您让步时,您应该执行yield item。这里itemitems 数组的一个实例。所以也需要准备。

编辑:此链接有不同的方法:https://stackoverflow.com/a/11483295/1160106

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多