Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: get collection of attributes for a model

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.

like image 631
futureshocked Avatar asked Sep 07 '25 10:09

futureshocked


2 Answers

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!

like image 66
Syed Aslam Avatar answered Sep 09 '25 06:09

Syed Aslam


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.

like image 41
Heikki Avatar answered Sep 09 '25 07:09

Heikki