ardavis
ardavis

Reputation: 9895

Rails - Avoid Repetition in Tables

I have a table of data in which I go through each user attribute, and display it in a table. This seems like a lot of repetition, even though the words are not the same, the process for each attribute is. Is there a way to automatically make a table row with a header of attribute.titleize and a data cell of user.attribute?

%table
  %tr
    %th First Name
    %td= @user.first_name
  %tr
    %th Middle Name
    %td= @user.middle_name
  %tr
    %th Last Name
    %td= @user.last_name

Upvotes: 1

Views: 259

Answers (2)

Brandan
Brandan

Reputation: 14983

You could make an _attribute partial to render a single row of the table:

# app/views/users/_attribute.html.haml
%tr
  %th= attribute.first.titleize
  %td= attribute.second

# app/views/users/show.html.haml
%table
  %tbody= render partial: 'attribute', collection: @user.attributes.to_a

If you don't want to render every attribute of User, create a method on the model that returns the attributes you do want and call that instead of @user.attributes:

# app/models/user.rb
class User
  def public_attributes
    attributes.slice('first_name', 'middle_name', 'last_name')
  end
end

Upvotes: 2

Jean
Jean

Reputation: 5411

Maybe you could use a partial.

http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

Upvotes: 0

Related Questions