conditional order field in has_many

I'd like the change the order field in a has_many relationship based on the value of one of my other fields. Is this possible?

In this case my parent model is Quiz and the child is QuizQuestion. If a quiz's 'style' attribute is set to 'sequential' i'd like to get @quiz.questions back in order of quiz_questions.position, otherwise i'd like to get them back in order of quiz_questions.low_band.

So, something like the following (i know this doesn't work because self is the class here)

has_many :quiz_questions, :order => "#{self[:style] == sequential ? 'position' : 'low_band'}"

can i use a proc to set the order for example?

thanks, max

I'd like the change the order field in a has_many relationship based on the value of one of my other fields. Is this possible?

In this case my parent model is Quiz and the child is QuizQuestion. If a quiz's 'style' attribute is set to 'sequential' i'd like to get @quiz.questions back in order of quiz_questions.position, otherwise i'd like to get them back in order of quiz_questions.low_band.

So, something like the following (i know this doesn't work because self is the class here)

has_many :quiz_questions, :order => "#{self[:style] == sequential ? 'position' : 'low_band'}"

The order clause is an sql fragment, so you can't do quite what you've written. You can of course write an if statement in sql (although you would have to also join the parent table), and order by something like IF(foo = 'bar', position, low_band)

This wouldn't end up as a very efficient query though and feels quite nasty.

Fred

Frederick Cheung wrote: