chase dougherty
chase dougherty

Reputation: 131

How to filter by params and user input in Rails

I am trying to display only the rows that belong to certain states in my application. I can do it the long way in Javascript, but I would prefer to better understand Rails and queries in the controller. I want to take the users to another page and then show them only that the companies in that state. It would be great to not have to link them to another page. Does anyone know how to do this?

Here is what I have in my controller

  def vendors
    @vendors = Collective.where(sort: 'Vendor').all
    @vendors = @vendors.where(params[:state])
  end

My route

get '/vendors/:state', to: 'collectives#vendors'

Then I use the stereotypical method to print a table in a html.erb file.

<% @vendors.each do |company| %>

<tr>
  <td><%= company.name %></td>
  <td><%= company.state %></td>
 etc...

Upvotes: 1

Views: 1605

Answers (2)

Marlin Pierce
Marlin Pierce

Reputation: 10079

Should your controller code change the where as follows:

def vendors
  @vendors = Collective.where(sort: 'Vendor').all
  @vendors = @vendors.where(state: params[:state])
end

or better:

def vendors
  @vendors = Collective.where(sort: 'Vendor', state: params[:state])
end

Upvotes: 3

iGian
iGian

Reputation: 11183

Using sessions instead of url params.

This is more or less what you can do, sorry if it is not completly working for your case, just to give an idea.

# view collectives/index (or whatever you have)

<%= form_tag (controller: :collectives, action: :set_status_filter, method: :post) do %>
  <%= select_tag(:session_status_filter, options_for_select(@your_list_of_options_for_the_filter)) %>
  <%= submit_tag "Set filter" %>
<% end %>


# collectives controller

def index # or whatever, this is the page containing the form and the list to show
  @vendors = Collective.where(sort: 'Vendor').all
  if session[:session_status_filter] == # etcetera
    then @vendors = @vendors.where(state: session[:session_status_filter]) # for example
  else # another option just in case, etcetera
  end
end

def set_status_filter # this action is called by the form
  session[:session_status_filter] = params[:session_status_filter]
    respond_to do |format|
      format.html { redirect_to *** the view where the form is placed ***, notice: 'the filter is set to: ....' + session[:session_status_filter] } # after the session variable is set the redirects goes to index which uses the session to filter records
    end
end

params[:session_status_filter] is passed by the form to collectives#set_status_filter. The value is used to set the session variables. After that the action collectives#set_status_filter redirects to the index, or whatever page you placed the form and the list to show.

Upvotes: 1

Related Questions