0

我有一个名为 GuestOrder 的模型:

class GuestOrder < ActiveRecord::Base
end

# == Schema Information
#
# Table name: guest_orders
#
#  id             :integer         not null, primary key
#  notes          :string(255)
#  adults         :integer
#  children       :integer
#  created        :datetime
#  placed         :datetime
#  billed         :datetime
#  user_id        :integer
#  guest_table_id :integer
#  take_away_id   :integer
#  created_at     :datetime
#  updated_at     :datetime

和一个控制器

class ApiController < ApplicationController
  def getOrdersByDate
    @guest_orders = GuestOrder.where(:created_at => (params[:created]))
    render json: @guest_orders
  end
end

routes.rb

  match '/api/getOrdersByDate'

当我尝试在 url 中获取它时

http://localhost:3000/api/getOrdersByDate?:created=2012-4-5

我得到了所有不受日期限制的记录

在我得到的服务器中select * from guest_orders

Started GET "/api/getOrdersByDate?:created=2012-4-5" for 127.0.0.1 at 2012-04-06 13:19:59 +0530
  Processing by ApiController#getOrdersByDate as HTML
  Parameters: {":created"=>"2012-4-5"}
  GuestOrder Load (26.3ms)  SELECT "guest_orders".* FROM "guest_orders"
Completed 200 OK in 47ms (Views: 1.5ms | ActiveRecord: 26.3ms)


Started GET "/api/getOrdersByDate?:created=2012-4-5" for 127.0.0.1 at 2012-04-06 13:21:21 +0530
  Processing by ApiController#getOrdersByDate as HTML
  Parameters: {":created"=>"2012-4-5"}
  GuestOrder Load (1.7ms)  SELECT "guest_orders".* FROM "guest_orders"
Completed 200 OK in 47ms (Views: 1.4ms | ActiveRecord: 1.7ms)

我的数据库中的记录有日期记录2012-03-22, 2012-04-05, 2012-04-06

如何查询getOrdersByDate以获取特定日期的记录。

4

2 回答 2

2

您的请求中不需要冒号,HashWithIndifferentAccess将为您进行 sym 查找。

http://localhost:3000/api/getOrdersByDate?created=2012-4-5

但是这个问题看起来很有趣,因为将 a 传递nil给 where 条件应该会导致以下查询:

SELECT "guest_orders".* FROM "guest_orders" WHERE "created_at" IS NULL

在您的情况下,缺少整个 SQL WHERE 条件。

更新#1

似乎需要重新加载。

要获取某个日期的记录,您可以使用以下方法:

time = Time.zone.parse(params[:created])
range = time.beginning_of_day..time.end_of_day
@guest_orders = GuestOrder.where(:created_at => range)

更新#2

如果您有开始和结束日期:

t_start = Time.zone.parse(params[:start])
t_end = Time.zone.parse(params[:end])
range = t_start.beginning_of_day..t_end.end_of_day
@guest_orders = GuestOrder.where(:created_at => range)
于 2012-04-06T08:05:58.673 回答
-1

您可以使用此查询按日期获取记录

    @results = GuestOrder.where("created_at = ? ", params[:created])

尝试一下

于 2012-04-06T08:07:40.047 回答