Reputation: 719
When searching for a solution, I found this on StackOverflow: Generate an HTML table from an array of hashes in Ruby.
This works great, but I'm a new programmer, and can't get it to work with rails. I have a database table called products. Each product has a field called data that stores a hash. This hash looks like:
{"type"=>"book", "price"=>"7.99"}
I am using haml, and my view right now looks like: (this is just printing out the hash):
- @products.each do |product|
=product.name
=product.data #THIS PRINTS A HASH LIKE THE ONE ABOVE
%hr
So now, I want to have the keys (for example, type and price) to be in the table head as 's, and each products values to be the 's. But I also want to have "static" columns, that aren't generated from the hash, like the product name. Here's a picture:
Upvotes: 1
Views: 537
Reputation: 33722
The StackOverflow article you referenced works great if you read your data from another source other than a database, e.g. from a YAML or CSV file, and then format it as HTML.
The advantage of the approach in the article is that it's flexible in regards what keys are used in the Hash(es), e.g. you have a flexible "schema". Depending on your input data, the formatted HTML table can contain different columns.
In a Rails application on the other hand you typically have an underlying database with a fixed schema, e.g. the attributes (keys) are well known in advance, and are defined in your migrations and are referenced in your model. Because the attributes are fixed, the HTML or HAML form is fixed, not variable as in the first case, and the form can be just provided as a template file.
That's why you have the views in Rails under app/views/your-model-name/
The example from @rails-guy shows you how such a fixed form for your Product model would look like for the index action.
See also: http://guides.rubyonrails.org/layouts_and_rendering.html
and: http://guides.rubyonrails.org/ (under Views)
Upvotes: 1
Reputation: 3866
You can simple get your values like this:
%table
%thead
%tr
%th
Name
%th
Type
%th
Price
%tbody
- @products.each do |product|
%tr
%td
= product.name
%td
= product.data["type"] unless product.data.nil?
%td
= product.data["price"] unless product.data.nil?
Upvotes: 1