Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Easy way to display all fields in view

OK I'm sure I'm missing something here, but please forgive me I'm new to Rails.

Is there some way in Rails to display all the fields for an object rather than specifying each?

In my show.html template rather than going

<p>Name: <%=h @user.full_name %></p>
<p>Email: <%=h @user.email %></p>

I just want a oneliner to do this without having to type out each of the 15 or so fields I have. Its an admin page so its fine if all the fields are shown (id, created_at, etc.) If this was PHP it would take me about 5 secs using foreach, but I've googled (on the wrong things obviously) for an hour with no luck.

Thanks!

like image 866
Michael Avatar asked Jun 23 '09 07:06

Michael


3 Answers

I suppose you want to display all attributes of a row from database table which is defined as ActiveRecord model. You can use class method column_names (every ActiveRecord model has it), which returns names of table columns in an array.

<%= User.column_names.collect { |col_name| "#{col_name.capitalize}: <p>#{@user[col_name]}</p>" }.join("\n") %>
like image 97
Lukas Stejskal Avatar answered Nov 17 '22 16:11

Lukas Stejskal


Something like

<% for attribute in @user.attributes.keys %>
  <p><%= attribute.humanize %> <%= @user.attributes[attribute].to_s %></p>
<% end %>

could do the trick.

Matt

like image 38
Matt Avatar answered Nov 17 '22 16:11

Matt


<%= debug @user %>

simple way to show the object... that is what I usually use anyway!

like image 2
Joel Grannas Avatar answered Nov 17 '22 16:11

Joel Grannas