Conditional order for nested model based on field

北慕城南 提交于 2019-12-11 12:11:16

问题


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


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/5306923/conditional-order-for-nested-model-based-on-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!