Ruby on Rails HTML-Table Generator
@ChrisH: Representing table using two arrays won't give more control. I would suggest the following: table_helper
erb snippet -
collection_table(@posts, {}, :id => 'posts', :class => 'summary') do |header, body|
header.column :title
header.column :category
header.column :author
header.column :publish_date, 'Date< br \>Published'
header.column :num_comments, '# Comments'
header.column :num_trackbacks, '# Trackbacks'
body.alternate = true
body.build do |row, post, index|
row.category post.category.name
row.author post.author.name
row.publish_date time_ago_in_words(post.published_on)
row.num_comments post.comments.empty? ? '-' : post.comments.size
row.num_trackbacks post.trackbacks.empty? ? '-' : post.trackbacks.size
end
end
In Rails 3.1, how can I create an HTML table generator that uses block style formatting
I just came up with this:
A few points:
- The line
@columns = []
is a reset so you can call it more than once. - The
yield
in the custom_table_for calls the block that you pass it. - The
block
in the column method is stored and called incustom_table_for
if it is set.
I included a sample class to show the usage too.
please note I did this outside of a rails app and you almost certainly want to use http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag instead of the p "<table>"
this is merely for sample purposes when you run it in the console.
module TableHelper
def custom_table_for(items)
@columns = []
yield
p "<table>"
@columns.each do |c|
p "<th>#{c[:value]}</th>"
end
items.each do |e|
p "<tr>"
@columns.each do |c|
e[c[:name]] = c[:block].call(e[c[:name]]) if c[:block]
p "<td>#{e[c[:name]]}</td>"
end
p "</tr>"
end
p "</table>"
end
def column(name, value = nil, &block)
value = name unless value
@columns << {:name => name, :value => value, :block => block}
end
end
class ExampleTable
include TableHelper
def test
@users = [{:email => "Email 1", :username => "Test User"}, {:email => "Email 2", :username => "Test User 2"}]
custom_table_for @users do
column :email, "Email"
column :username do |user|
user.upcase
end
end
end
end
et = ExampleTable.new
et.test
UPDATE
I migrated this to rails to use content_tags
module TableHelper
def custom_table_for(items)
@columns = []
yield
content_tag :table do
thead + tbody(items)
end
end
def thead
content_tag :thead do
content_tag :tr do
@columns.each do |c|
concat(content_tag(:th, c[:value]))
end
end
end
end
def tbody(items)
content_tag :tbody do
items.each { |e|
concat(content_tag(:tr){
@columns.each { |c|
e[c[:name]] = c[:block].call(e[c[:name]]) if c[:block]
concat(content_tag(:td, e[c[:name]]))
}
})
}
end
end
def column(name, value = nil, &block)
value = name unless value
@columns << {:name => name, :value => value, :block => block}
end
end
Generate an HTML table from an array of hashes in Ruby
Use the XMLBuilder for this:
data = [{"col1"=>"v1", "col2"=>"v2"}, {"col1"=>"v3", "col2"=>"v4"}]
xm = Builder::XmlMarkup.new(:indent => 2)
xm.table {
xm.tr { data[0].keys.each { |key| xm.th(key)}}
data.each { |row| xm.tr { row.values.each { |value| xm.td(value)}}}
}
puts "#{xm}"
Output
<table>
<tr>
<th>col1</th>
<th>col2</th>
</tr>
<tr>
<td>v1</td>
<td>v2</td>
</tr>
<tr>
<td>v3</td>
<td>v4</td>
</tr>
</table>
How can I print my database as a table on html page?
Assuming that you've successfully inserted everything into the DB, only thing left to do is just to use that @hmrc_rates
variable in your index.html.erb
view to display every DB row in a table.
For that you need to loop through each row in that variable and that would be something like:
<table>
<thead>
<th>Country</th>
<th>Currency</th>
<th>Currency Code</th>
<th>Units per Pound</th>
<th>Start Date</th>
<th>End Date</th>
</thead>
<tbody>
<% @hmrc_rates.each do |hmrc_rate| %>
<tr>
<td>
<%= hmrc_rate.country %>
</td>
<td>
<%= hmrc_rate.currency %>
</td>
<td>
<%= hmrc_rate.curr_code %>
</td>
<td>
<%= hmrc_rate.units_per_pound %>
</td>
<td>
<%= hmrc_rate.start_date %>
</td>
<td>
<%= hmrc_rate.end_date %>
</td>
</tr>
<% end %>
</tbody>
</table>
You can then apply your own styling.
Or you can use one of the table generators suggested in this SO post.
How to automatically generate rows in Html/Rails?
Use in_groups_of
for this (https://apidock.com/rails/Array/in_groups_of). Example:
<table>
<% products.ascend_by_name.in_groups_of(3, false) do |product_group| %>
<tr>
<% product_group.each do |product| %>
<td id="product_<%= product.id %>">
#-CONTENT HERE-#
</td>
<% end %>
</tr>
<% end %>
</table>
visual sql query generator for ruby on rails
This would need a lot of TLC to get to be like the MS Access Query, but you could use the Ransack gem to accomplish the queries and nested associations.
http://railscasts.com/episodes/370-ransack
Rails daily calendar with html table
One way to implement the required functionality would be to use the Calendar Helper gem to generate the calendar, and populate the details appropriately based on the param indicating which professional is selected.
How to Generate Tables as New Columns Instead of Rows?
You're creating new rows on every iteration of the loop. Rather than creating new rows and cells on every iteration, you should create only new cells inside loop. This might come at the cost of having to use more than one loop.
Print hash on table html - Ruby on rails
As David already said, with your input, it will be really difficult to achieve what you need. Since it was fun, I fixed it, but I do believe that it should be fixed somewhere higher in your code (I hope you're using Ruby 2.5+, if not, let me know which version you are on).
def fix_my_data(data)
data.group_by { |x| x[:id_control_access] }
.transform_values do |v|
v.map { |h| h.slice(:input, :output) }
.group_by { |h| h.keys.first }.values.inject(:zip).map { |x,y| x.merge(y.to_h) }
end
end
If you pass your array into this function, it will return this:
{1=>[{:input=>"Antena 1", :output=>"Antena 2"}, {:input=>"Antena 5"}],
2=>[{:input=>"Antena 3", :output=>"Antena 4"}]}
Which should be really simple to generate HTML with, like so:
<tr>
<% @data[control_access[:id_control_access]].each do |antenna| %>
<td><%= antenna[:input] %></td>
<td><%= antenna[:output] %></td>
<% end %>
</tr>
I'm pretty sure fix_my_data
can be written in a bit simpler way, but as I mentioned, it's a late place to be fixing the data.
Related Topics
Simulating Race Conditions in Rspec Unit Tests
Error While Installing Ruby 1.9.3
Colon in the Front: Yaml Syntax
Download File from S3 to Rails 4 App
"Error: Sql.H Not Found" When Installing Ruby-Odbc Gem on Ubuntu
Why Does Psych Yaml Interpreter Add Line Breaks Around 80 Characters
Error Nomethoderror: Undefined Method 'Debug_Rjs=' for Actionview::Base:Class
Ruby - Problems with Expect and Pty
Using %I and %I Symbol Array Literal
What Purpose Can Anonymous Modules Serve
Generating Sequential Numbers in Multi-User Saas Application
Emacs Ruby Method Parameter Indentation
Zip Up All Paperclip Attachments Stored on S3
"Cannot Load Such File - Rubygems/Defaults/Operating_System" When Installing Ruby 2.0.0