ricky116
ricky116

Reputation: 774

Native Ordering of a Model's Attributes

Does anyone know how Rails orders a model's attributes natively?

My issue is this:

I have a model I have been using for a long time called Device. In devices/show.html.erb I show its attributes using something akin to:

<% @device.attributes.each do |k,v| %>
  <tr>
    <td><%= k %></td>
    <td><%= v %></td>
  </tr>
<% end %>

I have decided to add an attribute that is related to the 5th attribute in the model's attributes, but when I run the create_column migration for it, it appears at the end of this list (as it is the last attribute to be added).

I suspect Rails orders its attributes by column-creation time, as I have attempted to move the column to the correct place in my database, and declare the attribute sooner in my attr_accessible list, to no avail. Moving the column in schema.rb and rebuilding the database would probably work, but this is something I can't do. I could hack it into the right spot in the view, but I'm wondering if there is a better solution first.

Is there any way I can do this without enforcing ordering across the whole attribute list?

Upvotes: 0

Views: 65

Answers (2)

DiegoSalazar
DiegoSalazar

Reputation: 13521

Rails migrations lets you specify where to add a column with the :after option:

add_column :your_table, :column_name, :data_type, after: :related_column

This could help. But, as this is a presentation concern, I'd order the attributes in a helper.

Upvotes: 1

Abdo
Abdo

Reputation: 14051

How about doing something like this:

1- Get the column_names (if you don't want to do it manually)

column_names = Device.column_names.inject([]) { |arr,e| arr.push(e) }

2- Modify the order that you want (i.e, a column name that you care about)

3- Evaluate each on @device

column_names.each_with_object({}) { |m, hash| hash[m] = @device.send(m) }

Upvotes: 1

Related Questions