繁体   English   中英

Rails 4:按2种不同的作用域/类方法排序

[英]Rails 4: Sorting by 2 different scopes/class methods

我正在尝试按将来的事件然后按已经结束的事件对事件进行排序。 我尝试使用2个不同的作用域,但现在正在考虑可能需要使用类方法。 在语法上,我只是在努力如何编写这些方法。

event.rb

def active
 self.event_date > Time.now
end

def inactive
 self.event_date < Time.now
end

“ event_date”是事件表中的日期时间列。

events_controller.rb

def index
 @events = Event.all.sort_by {|a,b| [a.active, b.inactive]}
end

有了这段代码,我得到一个错误:“ nil:NilClass的未定义方法'inactive'”,但是我尝试了几种不同的方式,但似乎无法弄清楚如何编写。

您的方法将在通过数据库运行后执行,并且速度很慢。

这可能可以改进:

模型

scope :active, -> { where('event_date >= ?', Time.now) }
scope :inactive, -> { where('event_date < ?', Time.now) }

控制者

@active_events = Event.active
@inactive_events = Event.inactive

@events = @active_events + @inactive_events

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM