根据现场的嵌套模式条件秩序 [英] Conditional order for nested model based on field

查看:90
本文介绍了根据现场的嵌套模式条件秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有HAS_MANY结果的事件模型。我想基于事件现场订购的结果。

I have an Event model which has_many Results. I want to order the results based on a field in Event.

我目前有在事件:

  has_many :results, :dependent => :destroy, :include => [:event], 
    :order   => "IF(self.etype = 'Stroke', 'results.score ASC', 'results.score DESC')"

...但是这deosn't工作。有没有更好的方式与named_scope为例做到这一点? 对不起,我stupidy,我是新来的Rails。

...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.

推荐答案

试试这个:

has_many :results, :dependent => :destroy, :include => [:event], 
  :order   => '#{(self.etype == "Stroke") ? 
                  "results.score ASC" : "results.score DESC"}'

在一个带引号的字符串或纯红宝石code作为一个属性值,它得到的类加载的时间进行评估。在这种情况下,而不是一个 A实例类。由于用户想要改变 ORDER BY 根据在手的条件在对象上的属性的价值取向应该用侧单引号。在这种情况下,是一个实例

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.

这篇关于根据现场的嵌套模式条件秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆