Lennart Koopmann
Lennart Koopmann

Reputation: 21079

Rails: Ordering through a has_one relation

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.

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

Upvotes: 1

Views: 1038

Answers (2)

vladr
vladr

Reputation: 66721

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.

Upvotes: 1

Cody Caughlan
Cody Caughlan

Reputation: 32748

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.

Upvotes: 0

Related Questions