Ruby on Rails: get a set of attributes for a model

I have a model with many attributes, and you created a series of pages to collect all the relevant data. On the last page I want to show the user all the data collected.

I could create this page by manually typing all the labels and values ​​for each attribute, but I expect that such a tedious and repetitive task has already been solved by someone, in 3-4 lines of code.

At this point, I am only prototyping so that it does not look good.

Does anyone have any suggestions on how to quickly print all the attributes of a model on the screen?

I thought something like this:

If @my_data_model is an instance variable for which I want to print attributes, then:

<%= show_attributes @my_data_model %>

displays attribute values ​​with their labels.

Thanks pending.

+3
source share
3 answers

I am doing this for one of my projects:

First, I define an array of columns that I don't need as timestamp columns:

<% @rejects = ["id", "created_at", "updated_at" %> 

Then from the object I delete these columns,

<% @columns = Patient.column_names.reject { |c| @rejects.include?(c) } %>

Then I repeat 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!

+5
source

I used this as a general view for the 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 it resource_classreturns the current class of the model and the resourcecurrent instance.

+1
source

Thanks everyone

I create a solution based on your recommendations:

<% @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 %>

Usage <%= @patient[i] %>did not work for me, possibly because I use Mongomapper as my ORM.

0
source

Source: https://habr.com/ru/post/1784885/


All Articles