Reputation: 2115
I have a model with a lot of attributes, and have build a series of pages to collect all the relevant data. In the last page, I want to show the user all the collected data.
I could create this page by manually typing all the labels and values for each attribute, but I expect that this kind of tedious and repetitive task has already been solved by someone so that in 3-4 lines of code.
At this stage I am only prototyping so this doesn't need to look good.
Anyone has any suggestions as to how to quickly print on the screen all attributes of a model?
I was thinking something like this:
If @my_data_model is the instance variable of which I want to print the attributes, then:
<%= show_attributes @my_data_model %>
would output the attribute values with their labels.
Thanks in anticipation.
Upvotes: 4
Views: 5173
Reputation: 2115
Thank you all,
I build a solution based on your recommendations like this:
<% @rejects = ["_id", "created_at", "updated_at"] %>
<% @columns = Agency.column_names - @rejects %>
<% @columns.each_with_index do |c, i| %>
<p id="p<%= i %>" class="check">
<span class="title"><%= c %>:</span>
<span class="value"><%= @agency.send(c) %></span>
</p>
<% end %>
Using <%= @patient[i] %>
didn't work for me, probably because I am using Mongomapper as my ORM.
Upvotes: 0
Reputation: 15417
I have been using this as a generic show view for inheritated_resources gem.
%h2= resource_class.model_name.human
%table
- resource_class.column_names.each do |column_name|
%tr{ :class => (cycle "odd", "even") }
%td= resource_class.human_attribute_name(column_name)
- if resource[column_name].respond_to?(:strftime)
%td= l resource.send(column_name)
- else
%td= resource.send(column_name)
There resource_class
returns the current model class and resource
the current instance of it.
Upvotes: 1
Reputation: 8807
I am doing that for one of my projects like this:
First I define an array of the columns I don't want like the timestamp columns:
<% @rejects = ["id", "created_at", "updated_at" %>
Then from the object I remove those columns;
<% @columns = Patient.column_names.reject { |c| @rejects.include?(c) } %>
Then I iterate through the column_names and print out the entered information:
<h2>Is the following information correct?</h2>
<div class="checks">
<h3>Patient details</h3>
<% @columns.each_with_index do |c, i| %>
<p id="p<%= i %>" class="check">
<span class="title"><%= c %>:</span>
<span class="value"><%= @patient[i] %></span>
<span class="valid">
<img src="../../images/icons/tick.png" alt="green tick">
</span>
</p>
<% end %>
</div>
Hope this helps!
Upvotes: 6