Okay, so this relates to the issue I explained earlier w/ the to_csv plugin (just for context).

@object.class.column_names will give an array of your table columns, in the same order as they appear in your database table.

@object.attribute_names give you an array of table columns (i'm using "table columns" and "attributes" interchangeably, which works for my particular application), sorted alphabetically.

@object.attributes.keys also gives you an array of table columns (again, using the term loosely), but in a seemingly random order (if someone can explain the order here, please let me know).

For my purposes, @object.attributes.keys works the best, so I can write the CSV like this:

csv << first.attributes.keys # header row
each do | record |
  csv << record.attributes.values
end

So here are my questions:
1. Why the inconsistencies in the ordering for essentially the same data? I'd at least like to see the ability to pass :order as an option. Maybe :default is the order in the table, and :alphabetical would be... well, alphabetical. I suspect the random order in the third option is because the keys are initially derived from @object.attributes which is a hash so the order isn't relevant.

2. (Here's my REAL question) Let's assume I want the order to be similar to if I had used @object.class.column_names. Does anyone know of a simple way to order @object.attributes? I was hoping for the :order option, but no dice that I'm aware of. Here's what I'm looking at currently:

@ordered_attributes = @object.attributes.sort_by { |key,value| @object.class.column_names.index(key) || 0 }

Any suggestions? (sorry for the long post... trying to avoid the lack of context issue we had w/ the last one)



_______________________________________________
Sdruby mailing list
[email protected]
http://lists.sdruby.com/mailman/listinfo/sdruby

Reply via email to