0

I am trying to implement a filter. I have a model with column status and I have defined enum status for that column inorder to make it readable. And these statuses are fixed.

model

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

And I am trying to filter the table based on the status given by the user. The result is filtered only if the user enter the complete name of status like preproduction. The controller is as follows:

controller

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

As you can see I am using params to query.

My current form tag looks like this

index

<%= form_tag productions_path, :method => 'get', :id=> "contacts_search" do %>
  <p>
    <%= text_field_tag :filter, params[:filter] %>
    <%= submit_tag "Filter", :name => nil %>
  </p>
  <div id="cresults_div"><%= render 'cresults'%> </div>
<% end %>

I have some fixed statuses as follows:

Production.statuses => {"Preproduction"=>1, "Postproduction"=>2, "Completed"=>3}

Since I am querying the controller with the help of params I cant directly use f.select like suggested in some answers. How can I get these keywords Preproduction Postproduction Completed in ad drop down of this text field ?

user3576036
  • 1,335
  • 2
  • 23
  • 51
  • Possible duplicate of [How to have a drop down – inye Dec 01 '17 at 12:02
  • since you are using `form_tag` so its not possible to use `f.select` instead of that you can use `select_tag` helper. – Anand Dec 01 '17 at 12:05
  • @Gabbar i want to retain `filter` attribute and `params[filter]`. So I tried this `<%= select_tag "filter", options_from_collection_for_select(Production.statuses) :filter, params[:filter] %>` . I am having difficult time getting it right. – user3576036 Dec 01 '17 at 12:16
  • lets try the given solution below, hopefully it can help you. let me know for further guidance. – Anand Dec 01 '17 at 12:23
  • Yeah got it. I added what you answered in select tag and I had to make some changes in the controller. Looks like you edited the answer. That's exactly what I did. – user3576036 Dec 01 '17 at 12:26

1 Answers1

1
<%= select_tag :'filter', options_for_select(Production.statuses, params[:filter]), include_blank: '--Select One Option--' %>

in controller: -

def index
  if params[:filter]
    @productions = Production.where(status: params[:filter])
  else
    @productions = Production.all
  end    
end
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Anand
  • 6,457
  • 3
  • 12
  • 26