代码之家  ›  专栏  ›  技术社区  ›  user3576036

如何根据枚举状态查询activerecord?

  •  0
  • user3576036  · 技术社区  · 8 年前

    我正在尝试对模型执行搜索/筛选操作 生产 基于列 地位 . 该列 status 是整数类型。后来为了可读性,我在上使用了枚举数据类型 地位 列如下。

    class Production < ApplicationRecord    
      enum status:{
        Preproduction:1,
        Postproduction: 2,
        Completed:3
      } 
    end
    

    然后,我开始开发搜索/过滤功能,根据用户给定的状态获取记录。

    productions\u控制器

    def filter
        if params[:filter]
          @productions = Production.where('productions.status like ?', "%#{params[:filter]}%")
        else
          @productions = Production.all
        end
      end
    

    看法

    <%= form_tag [:filter, :productions], :method => 'get' do %>
      <p>
        <%= text_field_tag :filter, params[:filter] %>
        <%= submit_tag "Filter", :status => nil %>
      </p>
    <% end %>
    

    现在,只有输入以下整数值,我才能正确查询记录 1 2 或 3 在文本字段中。当我进入这样的状态时 Preproduction 就像我分配的那样,我没有得到结果。我收到一张空白页。我怎样才能解决这个问题?我如何才能成功地接受字符串和查询?

    1 回复  |  直到 8 年前
        1
  •  1
  •   SteveTurczyn    8 年前

    你可以这样做。。。

    @productions = Production.where('productions.status like ?', "%#{Production.statuses[params[:filter]]}%")
    

    enum有一个复数类方法,所以enum status Production.statuses