有条件的地方

Where with a condition

我有一个 table 这样的:

Calendar
 - date
 - description
 - userid

我想通过用户 ID 获取用户给定月份的所有事件。

所以我知道获取用户标识的所有事件是:

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

我试过了(正如我在一些 post 中看到的那样)

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" =  AND (date ~= '%2016-...
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我做错了什么?

我想你的解决方案就在这里

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

请看下面link

我想对你有帮助

您可以尝试 "parsing" 您的列 date 使用 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)