如何使用 Rails 5.2 从 Arel 查询中的日期中提取一周?
How to extract a week from a date in Arel query with Rails 5.2?
我使用 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 中 ruby 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]]
)
我使用 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 中 ruby 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]]
)