我想为表格创建一个视图辅助方法,我可以传递任何对象和标题对象,它可以轻松地映射数据库中的标题和数据并创建表格。 我想让它通用,所以我可以在项目的任何地方使用它。 我尝试使用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,它将包含hash和@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
谢谢!
答案 0 :(得分:1)
对于功能齐全的方法,有可用的宝石(如datagrid)可以处理您描述的内容和其他功能,如排序,过滤等。除非您有充分的理由重新发明轮子,我建议调查那些替代品(谷歌“铁路数据表”或类似的东西)。
对于一个简单的方法,您可以利用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) %>
但正如你所知,这是非常基本的,在任何制作环境中都不是很有用。