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

On Feb 23, 7:17 pm, Max W. [email protected] wrote:

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 C. wrote:

On Feb 23, 7:17�pm, Max W. [email protected] wrote:

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

yeah, i’m inclined to agree re the nasty. It does work though: in case
anyone else stumbles across this, i have

has_many :quiz_questions, :dependent => :destroy, :include => [:quiz],
:order => “IF(quizzes.style = ‘sequential’, position, low_band)”

The extra include is the dodgy bit isn’t it. I’ll give it a go anyway.

Thanks!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs