Q:
How to display all database data to a html table in ruby on rails?
I am new to Ruby on Rails. I am struggling with fetching all the data from the database to a html table.
This is the controller that fetches the data from the db and pass it to a view.
@result = Result.all
and this is the view:
Name
<%= @result.name %>
Address
<%= @result.address %>
Contact No.
<%= @result.contactno %>
Age
<%= @result.age %>
Gender
<%= @result.gender %>
Date
<%= @result.date %>
A:
You can do this by looping through all of the results:
<% @result.each do |res| %>
<%= res.name %>
<% end %>
To use the index of the iteration, you can use the index operator:
<% @result.each_with_index do |res,index| %>
<%= res.name %>
<% end %>
A:
If you have more than one result, it's recommended that you use a method to loop through the result set:
<% @results.each do |result| %>
<%= result.name %>
<%= result.date %>
<%= result.gender %>
<%= result.age %>
<% end %>
or, alternatively, use a <% @results.each do |result| %> block in your view.
A:
In short, display it in a table, like this:
- @results.each do |row|
- row.each do |attribute|
- puts attribute.to_s
That will display each row, and each attribute in the table.
A:
Create view like this and run
<% @result.each do |result| %>
<%= result.name %>
<%= result.date %>
<%= result.gender %>
<%= result.age %>
<% end %>
And that will create a table like this :
+-----+-----+-------+-------+-------+------+--------+
| name| date| gender| age | address| contact| city |
+-----+-----+-------+-------+-------+------+--------+
| Joe | 03 | male | 30 | x | | Paris |
+-----+-----+-------+-------+-------+------+--------+
Update:
If you want to use form to update the rows, create view like this
<% @result.each do |result| %>
<%= result.name %>
<%= result.date %>
<%= result.gender %>
<%= result.age %>
<% end %>
And fill these inputs with their names, update button with id attribute_1_upadte so when click on that it will change values of input. Do not forget to set id for every input. I have updated code below for you:
" name="name" type="text">
" name="date" type="text">
" name="gender" type="text">
" name="age" type="text">
After click Update your table will change like this :
+-----+-----+-------+-------+-------+------+--------+
| name| date| gender| age | address| contact| city |
+-----+-----+-------+-------+-------+------+--------+
| Mike| 05 | male | 30 | x | | Paris |
+-----+-----+-------+-------+-------+------+--------+
Update: (if you want to fetch all your results without form)
<% @result.each do |result| %>
<%= result.name %>
<%= result.date %>
<%= result.gender %>
<%= result.age %>
<% end %>
After click update you will get table result like this :
+-----+-----+-------+-------+-------+------+--------+
| name| date| gender| age | address| contact| city |
+-----+-----+-------+-------+-------+------+--------+
| Mike| 05