2013-07-13 28 views
0

我有一个表Mnt_Items,用于存储在last_mnt中完成的上次维护的日期。此外,该表还存储mnt_frequence中的维护之间的天数。 我要作出这样的呈现需要维护所有项目的看法,但我得到的错误:如何在条件中设置日期的格式

SQLite3::SQLException: near "23": syntax error: SELECT "mnt_items".* FROM "mnt_items" WHERE (last_mnt > 2013-06-22 23:58:41 UTC) 

我的模型和控制器如下:

class MntItem < ActiveRecord::Base 
    named_scope :needs_maintain, :conditions => "last_mnt > " + -20.days.from_now.to_s 
end 

class MntItemsController < ApplicationController 
    def index 
    @mnt_items = MntItem.needs_maintain 

    respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @mnt_items } 
    end 
end 

任何建议是什么原因造成的错误,或者如何实现?

+0

您是否尝试过封闭单引号(')内的日期值? – Ma3x

+0

Gylaz给了我一个解决方案。谢谢 – Dajoh

回答

0

让轨道做的工作适合你:

scope :needs_maintain, -> (day_count) { where('last_mnt > ?', day_count.days.from_now) } 

然后调用它:

MntItem.needs_maintain(20) 
+0

是不是我submtted rails代码? – Dajoh

+0

我可以问你,如果我想要将硬编码的“20”替换为mnt_frequence,我该如何实现它? – Dajoh

+0

我的意思是,让rails处理Date对象到SQL查询格式的转换。我更新了示例以显示如何传递值。另外,使用'scope'而不是'named_scope'。 – gylaz

相关问题