2017-06-17 64 views
1

我有这样的一个表:凡符合条件

Calendar 
- date 
- description 
- userid 

而且我想获得用户通过它用户标识的特定月份的所有事件。

所以我知道,要得到所有事件的用户ID是:

Calendar.where(userid: params[:id]) 

我试过(正如我在一些岗位中看到的已经在这里)

Calendar.where(userid: params[:id]).where("date ~= ?", '%2016-12%') 

因此,这应该给我所有事件从2016年的第12个月,而是我有:

ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: date ~= unknown 
LINE 1: ...endars" WHERE "calendars"."userid" = $1 AND (date ~= '%2016-... 
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 

我做错了什么?

+0

是您的日期列日期时间类型? –

+0

是的,为什么? – Difender

回答

1

你可以尝试 “解析” 你列date到char使用to_char Postgresql函数传递列和所需的格式:

SELECT * 
FROM calendars 
WHERE to_char(date, 'YYYY-MM-DD') LIKE '%2016-12%' 

所以,你可以使用ActiveRecord#find_by_sql

query = "SELECT * FROM calendars WHERE to_char(date, 'YYYY-MM-DD') LIKE '%2016-12%'" 
Calendar.find_by_sql(query) 
+1

是的,这是它!非常感谢 ! – Difender

1

我认为您的解决方案是在这里

def index 
    @events = Calendar.where(userid: params[:id]).all 
    @event_months = @events.group_by { |t| t.date.month } // month is a given name 
end 

请参阅下面的链接

https://stackoverflow.com/a/18862762/8175208

我想会帮助你

+0

您不需要拨打任何电话。 – bkunzi01