user3576036
user3576036

Reputation: 1435

How to query the activerecord based on the enum status?

I am trying implement a search/filter action on a model Production based on a column status. The column status is of integer type. Later for the purpose of readability I used enum datatype on status column as follows.

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

Then I started to work on a search/filter functionality to fetch the record based on the status given by the user.

productions_controller

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

view

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

Now I am able to query the record properly only if I enter the integer values like 1 2 or 3 in the text field. When I enter the status like Preproduction like I assigned, I am not getting the result. I am getting a blank page. How can I fix this ? How can I make it to accept the string and query successfully ?

Upvotes: 0

Views: 1582

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36870

You can do this...

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

Enums have a pluralized class method, so enum status in Production has a hash Production.statuses which looks like your status hash but with the symbols changed into strings.

Upvotes: 1

Related Questions