Ruby on Rails - Railscast #213 Calendar sort by datetime not date

不羁的心 提交于 2019-12-13 07:15:45

问题


I am building an app that involves a calendar. I found that the railscast for building a calendar although dated proved to be very helpful. I have everything up and running I am just trying to allow for the contents on each date to be organized by the datetime and not just the date so they appear in the right chronological order.

My current controller looks like this:

def index
  @lessons = Lesson.all
  @lesson_by_date = @lessons.group_by { |i| i.lesson_date.to_date }
  @date = params[:date] ? Date.parse(params[:date]) : Date.today
end

Any help would be greatly appreciated. Thanks


回答1:


I'm going off the assumption your question is how do I organize my @lessons by datetime. There are a few different scenarios I'll mention. I'm a bit limited since I don't know from your post how you've organized your schema for the table, but I think the controller gives me a ballpark idea.

1) You should replace:

@lesson = Lesson.all
@lesson_by_date = @lessons.group_by { |i| i.lesson_date.to_date }

with something that's quicker:

@lesson_by_date = Lesson.order('lesson_date')

2) If you're wondering why your current code isn't working it's because your group_by block is trying to convert i.lesson_date to a date IE to_date. Instead you may want to try to_datetime.

3) I would review http://apidock.com/rails/ActiveRecord/QueryMethods/order



来源:https://stackoverflow.com/questions/29524165/ruby-on-rails-railscast-213-calendar-sort-by-datetime-not-date

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