What is the correct way to implement filters in Rails?

1

Good morning!

Currently, I have an application with a simple CRUD, and I'm creating a new view to display the records. In that view, I'm including some filters that are parameterized links to be sent to the controller and filter the list with those records. My question is: what is the best (smarter) way to create a filter on the Rail?

Here's how it's implemented:

In the Main view, we have a column with the records and a column with the filters:

  • view / controller-action / path
    index.html.erb / where we are # index / where-we

  • / li>

Then there's something like this:

Controller:

def index

end

def index_filtro
    "Aqui os registros nao filrados através de uma nova query incluindo o parâmetro enviado pela view"
    render index
end

Routes:

get '/onde-estamos', to: 'onde#index', as: 'onde-estamos'
get '/onde-estamos/filtros/:f', to: 'onde#index-filtro', as: 'onde-estamos-filtro'

This works, but I do not think that's the best way. This solution prevents me from being more flexible with filters, such as combining filters and so on. '

    
asked by anonymous 26.01.2017 / 14:19

1 answer

0

Friend, I think it would be ideal to use Filter Scope

An example usage:

Your Model:

class Dinosaur < ActiveRecord::Base
 scope :with_name, lambda {|parameter| where("name like ?", "%#{parameter}%")}     
 scope :taller_than, lambda {|parameter| where("height > ?", parameter)}

 def self.search(parameters)
   dinosaur_query = self.scoped
   parameters.each do |parameter, value|
     if not value.empty? and dinosaur_query.respond_to? parameter
       dinosaur_query = dinosaur_query.send(parameter, value) 
     end
   end
   dinosaur_query
 end
end

Your Controller:

@dinosaurs = Dinosaur.search(params)
    
27.01.2017 / 17:15