Conditional order for nested model based on field
I have an Event model which has_many Results. I want to order the results based on a field in Event.
I currently have in Event:
has_开发者_JS百科many :results, :dependent => :destroy, :include => [:event],
:order => "IF(self.etype = 'Stroke', 'results.score ASC', 'results.score DESC')"
...but this deosn't work. Is there a better way to do this with named_scope for example? Sorry for my stupidy, I am new to Rails.
Try this:
has_many :results, :dependent => :destroy, :include => [:event],
:order => '#{(self.etype == "Stroke") ?
"results.score ASC" : "results.score DESC"}'
When a quoted string OR a plain ruby code is used as an attribute value, it gets evaluated at the class loading time. In such a case, the self
is a class
rather than a instance of a class
. Since the user wants to change the ORDER BY
direction based on the value of an attribute on the object in hand condition should be enclosed in side single quote. In such cases the self
is an instance of the class
.
Does this solve it?
has_many :results, :dependent => :destroy, :include => [:event], :order => "IF(results.etype = 'Stroke', 'event.score ASC', 'event.score DESC')"
If not, what error is returned when you try to do this in the console:
Event.first.results
Try this:
in rails 3.0.x:
has_many :results, :dependent => :destroy, :include => [:event],
:order => "#{(proxy_owner.etype == 'Stroke') ?
'results.score ASC' : 'results.score DESC'}"
In rails 3.x.x:
has_many :results, :dependent => :destroy, :include => [:event],
:order => "#{(proxy_association.owner.etype == 'Stroke') ?
'results.score ASC' : 'results.score DESC'}"
Hope this helps.
精彩评论