【问题标题】:How to make universal generic view for tables?如何为表格制作通用通用视图?
【发布时间】:2016-05-13 12:23:30
【问题描述】:

我想为可以传递任何对象和表头对象的表创建一个视图辅助方法,它可以轻松地映射数据库中的表头和数据并创建表。 我想让它通用,这样我就可以在项目的任何地方使用它。 我尝试使用 content_tag 但不够成功。 我看到很多关于堆栈溢出的答案,但没有一个能满足我的兴趣。

感谢任何帮助。 这是我尝试做的专门针对附件模型的东西。

 def display_doc_table(columns, collection = {})

   thead = content_tag :thead do
     content_tag :tr do
      columns.collect {|column|  concat content_tag(:th,column[:display_name])}.join().html_safe
     end
   end

   tbody = content_tag :tbody do
    collection.collect { |elem|
      if elem.is_visible_to_all or (can? :manage, Attachment) 
        content_tag :tr do
          columns.collect { |column|
              concat content_tag(:td, link_to(elem.attributes[column[:name]], elem.document.url, data: { :colorbox => true, :colorbox_height => '700px', :colorbox_width => '700px', :colorbox_iframe => true }) , class: "remove_underline")
              concat content_tag(:td, link_to("Edit ",edit_attachment_path(elem)))
              concat content_tag(:td,"|")
              concat content_tag(:td, link_to(" Delete",attachment_path(elem), data: {method: :delete, confirm: "Are you sure?"}))        
      }.to_s.html_safe
    end
  end
    }.join().html_safe
   end

   content_tag :table, thead.concat(tbody)

end

但是我想要一些东西,比如我将传递@header,它将包含哈希和@docs 或@user,即模型的对象。 它将检查模型中是否存在操作 url,如果是,它将将该操作附加到@header,并将继续创建一个名为 Action 的列,该列将定义操作 url,如编辑和删除,否则它只会将表数据显示为每个@header。

类似这样的:

def table_for(@header, @user)
 if object has action url in it then
   append the action to header
create a table data as per header along with column Action or
just create a table data as per header.  
end

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 helpers view-helpers


    【解决方案1】:

    对于功能齐全的方法,有可用的 gem(如 datagrid)可以处理您所描述的内容和其他功能,如排序、过滤等。除非您有充分的理由重新发明轮子,我建议研究那些替代方案(谷歌“rails 数据表”或类似的东西)。

    对于基本方法,您可以利用 ActiveRecord 的反射能力:

    def table_for(relation, columns = relation.columns.map(&:name))      
      headers = columns.map(&:titleize).map {|h| "<th>#{h}</th>"}
      header_row = "<tr>#{headers.join}</tr>"
    
      rows = relation.all.map do |row|
        cells = columns.map {|attr| row.send(attr)}.map {|v| "<td>#{v}</td>"}
        "<tr>#{cells.join}</tr>"
      end
    
      "<table>#{[ header_row, rows ].flatten.join('\n')}</table>"
    end
    
    # view.html.erb
    
    <%= h table_for(User) %>
    

    但正如您所知,这是非常基本的,在任何生产环境中都不是很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      相关资源
      最近更新 更多