Ruby 来自 MySQL 的辛纳屈 table

Ruby Sinatra table from MySQL

我目前正在做一个项目,我必须从 MySQL 数据库中提取数据并使用 Ruby Sinatra 在 table 中显示数据。

我能够连接到数据库并提取数据并将其放入数组中。

数据库中 table 的示例

City Country Dallas USA Tokyo Japan

数组的示例

["Dallas, USA", "Tokyo, Japan"]

现在,我将如何显示数组以使其看起来与数据库中的 table 完全一样。或者,有没有办法可以将 table 从数据库完全复制到网页上?

感谢您的帮助!

your_app/routes.rb:

require 'sinatra'
require 'slim'

get '/' do

  raw_data = [
    "Dallas, USA", 
    "Tokyo,Japan", 
    "Munich,    Germany",
  ]

  @results = {}

  raw_data.each do |item|
    city, country = item.split(/, \s* /x)
    @results[city] = country
  end

  p results # {"Dallas"=>"USA", "Tokyo"=>"Japan", "Munich"=>"Germany"}

  slim :index 

end

your_app/views/layout.苗条:

doctype html 
html
  head 
    meta charset="utf-8"
    title Test
    css:
      th {text-align:left}
      table {width: 15em}
  body 
    h1 This is the Layout.  Find me in your_app/views/layout.slim
    == yield 

注意 css,它使列 headers 左对齐——否则 headers 列将居中。

your_app/views/index.苗条:

table 
  thead
    tr
      th City
      th Country

  tbody
  - @results.each do |city, country|
    tr
      td = city
      td = country

结果:

编辑:

要使用 jquery 程序 tablesorter,请下载 tablesorter,然后 unzip/untar 它,然后将新创建的目录 tablesorter-master 移动到目录 your_app/public/.

您可以使用这些文件:

your_app/views/layout.苗条:

doctype html 
html
  head 
    meta charset="utf-8"
    title Test
    link rel="stylesheet" type='text/css' href="tablesorter-master/themes/green/style.css"
  body 
    h1 This is the Layout.  Find me in your_app/views/layout.slim
    == yield 

    script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" !<= the link
    script src="tablesorter-master/jquery.tablesorter.js"
    script src="hookup_tablesorter.js"

your_app/public/hookup_tablesorter.js:

$(document).ready(function() 
  { 
    $("#myTable").tablesorter(); 
  } 
); 

your_app/views/index.苗条:

table id="myTable" class="tablesorter"
  thead
    tr
      th City
      th Country

  - @results.each do |city, country|
    tr
      td = city
      td = country

注意上面的变化。 Slim 自动添加一个 tbody 标签,因此在 Slim 模板中显式添加一个 tbody 标签会创建两个 tbody 标签,这会搞砸 tablesorter。

然后你会看到这个:

然后单击 headers 列将对行进行排序。您需要 link 和 jquery 文件的互联网连接。或者,您可以下载 jquery,并将其放在目录 your_app/public/ 中,然后 link 到它:

doctype html 
html
  head 
    meta charset="utf-8"
    title Test
    link rel="stylesheet" type='text/css' href="tablesorter-master/themes/green/style.css"
  body 
    h1 This is the Layout.  Find me in your_app/views/layout.slim
    == yield 

    script src="jquery.min.js"
    script src="tablesorter-master/jquery.tablesorter.js"
    script src="js_ready.js"

如果您不喜欢那种 table 风格,tablesorter 也有蓝色主题:

人们还创造了其他 styles