2013-03-20 35 views
0

我试图通过REST界面从Rails应用程序中提取JSON记录。我正在使用RABL来创建JSON。我想要比指定的created_at更大的记录。Rails REST使用url来筛选索引

在worequests控制器,我有这样的:

def index 
    if params[:created_at] != nil 
    @worequests = Worequest.find(params[:created_at]) 
    else 
    @worequests = Worequest.order(:created_at) 
end 

如果我进入浏览器这样的:

http://localhost:5000/worequests?created_at=2012-11-28%2016:37:29.253916 

我得到这个:

Couldn't find Worequest with id=2012-11-28 16:37:29.253916 

我复制了日期时间来自PG表格。

Question1

为什么找不到记录?

问题2

要使用大于,我应该能够使用像这样的网址是什么?

http://localhost:5000/worequests?created_at>2012-11-28%2016:37:29.253916 

问题3

如果我得到的工作,我将如何然后询问JSON?

http://localhost:5000/worequests?created_at>2012-11-28%2016:37:29.253916.json 

UPDATE1

感谢HungryCoder - 这现在工作:

http://localhost:5000/worequests?created_at=2013-01-01 

我得到的记录在该日期更大的索引列表。

但是,如何获得JSON?

我尝试这样做:

http://localhost:5000/worequests?created_at=2013-01-01.json 

回答

0

回答1

find方法需要的记录的ID。

如果你想使用created_at现场使用,其中或属性的辅助方法

@worequests = Worequest.where("created_at = ?", params[:created_at]) 

或过滤,

@worequests = Worequest.find_by_created_at(params[:created_at]) 

,或者

@worequests = Worequest.find_all_by_created_at(params[:created_at]) 

Worequest.find类似于Worequest.find_by_id(假设id是主键的名称)

答案2 你不能在查询字符串中使用这种格式。你可以把它放在单独的变量一样

http://localhost:5000/worequests?created_at=2012-11-28%2016:37:29.253916&compare=%3E 

所以,比较大于可能是这样:

if params[:compare] == '>' 
    @worequests = Worequest.where("created_at > ?", params[:created_at]) 
end 

'%3E' 是的URI编码版本>

答案3

http://localhost:5000/worequests.json?created_at>2012-11-28%2016:37:29.253916 
+0

感谢您的帮助。我将如何使它的搜索日期时间大于参数中的内容?只需将=改为> – Reddirt 2013-03-20 19:42:33

+0

是的,只需使用>。请检查示例逻辑的更新答案 – HungryCoder 2013-03-20 19:46:58

+0

谢谢 - 最后一个返回JSON! – Reddirt 2013-03-20 19:48:04