我无法从数据库中提取事件日期以正确顺序呈现。我在我的simple_form中使用bootstrap-datepicker供用户使用。我的事件控制器当前为:
```def index
@events = Event.order(start_date: :asc).where('start_date::date >= CURRENT_DATE')
end```
这些事件的确以正确的日期显示在页面上,但似乎只能按月排序,而忽略年份。例如,在2021年1月发生的事件将在2020年3月之前列出,因为1月在3月之前。
我尝试寻找ruby中的订购方法以及与其他文章一样进行搜索的方式,但是我没有成功。有什么想法吗?
日志:
```Started GET "/events" for ::1 at 2019-11-25 10:26:28 -0800
Processing by EventsController#index as HTML
Rendering events/index.html.erb within layouts/application
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/views/events/index.html.erb:10
Event Load (0.3ms) SELECT "events".* FROM "events" WHERE (start_date::date >= CURRENT_DATE) ORDER BY "events"."start_date" ASC
↳ app/views/events/index.html.erb:27
Rendered events/index.html.erb within layouts/application (4.4ms)
Completed 200 OK in 174ms (Views: 171.2ms | ActiveRecord: 0.6ms)```
application.js:
```//= require rails-ujs
//= require activestorage
//= require jquery
//= require jquery_ujs
//= require popper
//= require tether
//= require bootstrap-sprockets
//= require_tree .
//= require bootstrap-datepicker
$(function() {
$('input.datepicker').data({behaviour: "datepicker"}).datepicker();
});```
simple_form:
```<div class="event-box col-5 offset-3">
<br/>
<h1 align="center" style="font-size: 25px;">Create New Event</h1>
<%= simple_form_for @event do |f| %>
<%= f.input :title %>
<%= f.input :start_date, as: :string, input_html: { class: "datepicker" }%>
<%= f.input :end_date, as: :string, input_html: { class: "datepicker" }%>
<%= f.input :location %>
<%= f.input :details %>
<br />
<div align="center">
<%= f.submit 'Create', class: 'btn btn-primary' %>
</div>
<% end %>
<br/>
</div>
<script>
$('#datepicker').datepicker({format: 'mm-dd-yyyy'});
</script>```
事件表:
```create_table "events", force: :cascade do |t|
t.string "title"
t.string "start_date"
t.string "end_date"
t.string "location"
t.text "details"
t.integer "event_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "event"
t.index ["event_id"], name: "index_events_on_event_id"
end```
答案 0 :(得分:2)
这里的问题是start_date
被保存为字符串而不是时间。当您尝试按字符串排序时,它只是将输出按字母顺序排列,因此所有一月都将分组在一起。
如果您更改:
t.string "start_date"
收件人:
t.date_time "start_date"
它应该工作。您显然必须迁移现有数据。