如何使用Rails 5.2从Arel查询中的日期中提取一周?

问题描述

我使用Arel构建可重用和结构化的查询,但是环顾四周,我没有找到一种清晰有效的方法来更改提取日期以实际检索日历周。

我使用cweek Ruby方法,尝试在Postgres上构建以下查询:

week_series = Skill.joins(concepts_list).select(skills[:created_at].cweek,skills[:id].count.as("count")).group(skills[:created_at].cweek)

这是我对技能的基本要求:

### Base object
def skills
  Skill.arel_table
end

# Additional tables
def users
  User.arel_table
end

def organisations
  Organisation.arel_table
end

def themes
  Playground.arel_table.alias('themes')
end

def domains
  BusinessArea.arel_table.alias('domains')
end

def collections
  BusinessObject.arel_table.alias('collections')
end

# Queries
def concepts_list
  skills.
  join(users).on(skills[:owner_id].eq(users[:id])).
  join(organisations).on(skills[:organisation_id].eq(organisations[:id])).
  join(collections).on(skills[:business_object_id].eq(collections[:id])).
  join(domains).on(collections[:parent_id].eq(domains[:id]).and(collections[:parent_type].eq('BusinessArea'))).
  join(themes).on(domains[:playground_id].eq(themes[:id])).
  join_sources
end

def concepts_list_output
  [skills[:id],skills[:created_at],users[:user_name],users[:name],organisations[:code],themes[:code],domains[:code]]
end

解决方法

在postgresql中,红宝石cweek的等效项是EXTRACT/DATE_PART。如果您使用的是其他数据库,则可能会有所不同。

您追求的SQL是

DATE_PART('week',"skills"."created_at")

那只是一个NamedFunction

Arel::Nodes::NamedFunction.new(
  'DATE_PART',[Arel::Nodes.build_quoted('week'),skills[:created_at]]
)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...