views:

234

answers:

2

I am building a mechanism for sortable columns in tables. Every table represents a list of data so I call the database table "lists". Everything except the ordering of the columnpositions works. I want to display the columnpositions ordered by the field "position" but nothing changes even if I remove the :order statement.

  • list.rb :has_many :columns
  • column.rb :has_one :columnposition, :order => "position ASC"
  • columnposition.rb <- The positions are stored here as simple integers.

I can access list.column.columnposition.position with no problem so the relations themselves seem to work.

Why are the columnpositions not ordered by "position ASC"?

// Edit: I fetch the lists with @lists = List.find :all

A: 

I assume that the expression you are trying to order is

list.column

And you want that result to be ordered by position? Well, in this case the query is not "looking into" the columnposition association so it is not respecting any of its :order clause(s).

I am not sure why you need to make columnposition its own association, especially since you have it as a :has_one, so there is only 1 matching row.

I would just put that columnposition data as a column in the Column model and then you can order it the way you want in your single query.

Cody Caughlan
Putting the position into the columns table is not a good idea in this case because every column has it's own name and the position is user defined.
Lennart
So, Cody, any news on this one?
vladr
+1  A: 

Hi, Lenn,

The :order => "position ASC" option does not help at the level of your relation definition, as it is the lists that you want to order by column position, not the positions themselves.

Remove the :order => "position ASC" from the model, and try:

@lists = List.find(:all, :joins => { :columns => :column_positions }, \
  :order => 'column_positions.position ASC')

instead. Look at the generated SQL when running in development mode.

Cheers, V.

vladr