我有一个名为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
中查询以获取特定日期的记录。
答案 0 :(得分:2)
您的请求中不需要冒号,HashWithIndifferentAccess
可以为您执行sym查找。
http://localhost:3000/api/getOrdersByDate?created=2012-4-5
但问题看起来很有意思,因为将nil
传递到where条件会导致以下查询:
SELECT "guest_orders".* FROM "guest_orders" WHERE "created_at" IS NULL
在您的情况下,缺少整个SQL WHERE条件。
似乎需要重装。
要获取日期的记录,您可以使用以下方法:
time = Time.zone.parse(params[:created])
range = time.beginning_of_day..time.end_of_day
@guest_orders = GuestOrder.where(:created_at => range)
如果您有开始日期和结束日期:
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)
答案 1 :(得分:-1)
您可以使用此查询按日期获取记录
@results = GuestOrder.where("created_at = ? ", params[:created])
试试吧