使用Postgres按年份分组

时间:2018-09-26 04:18:23

标签: ruby-on-rails postgresql ruby-on-rails-5

我希望仅在created_at日期字段中按年份分组。我正在使用postgres,发现它与使用Mysql有所不同。

我希望仅显示年份并将其用于搜索参数。

我遇到以下错误:missing attribute: created_at

搜索表

<%= form_tag(page_path, method: :get) do %>
  <%= select_tag :select_year, options_for_select(@years.map { |m| m.created_at.year }) %>
  <%= submit_tag 'Search', name: nil %>
<% end %>

控制器(索引)

@trials = if params[:select_year]
  Product.where('extract(year from created_at) = ?', "#{params[:select_year]}")
  else
  Product.where('extract(year from created_at) = ?', Time.now.year))
  end

@years = Product.group('extract(year from created_at)').order('extract(year from created_at) DESC').select('extract(year from created_at)')

2 个答案:

答案 0 :(得分:2)

您选择的内容中缺少as

.select('extract(year from created_at) AS created_at_year')

然后您可以致电@years.map(&:created_at_year)

答案 1 :(得分:1)

产品#索引

def index
  #.....
  #Performance point of view
  @years_arrays = Product.order('extract(year from created_at) DESC').pluck('DISTINCT extract(year from created_at)')
end

查看搜索表

<%= form_tag(page_path, method: :get) do %>
  <%= select_tag :select_year, options_for_select(@years_arrays) %>
  <%= submit_tag 'Search', name: nil %>
<% end %>