What is the right way to implement filters in Rails?

Asked

Viewed 837 times

1

Good morning!

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

Follows how it is implemented:

In view Leading, 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 are

  • To create a filter, I create a new route (e.g., where-we/filters/:f ), create a new function that will take this parameter, and reuse the main view.

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'

That works, but I don’t think that’s the best way. This solution prevents me from being more flexible with filters, such as combining filters and so on. `

  • Send a request to the index route even with the parameters sent by query.Request: /where are we? filtro_1=value_2=value2.

  • I’ll refactor like this! Thank you!

1 answer

0


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

An example of use:

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)
  • Thank you Geilton. I gave a studied and I ended up finding the Scope Filters. I will unite with the solution for the routes sent by Matheus Silva.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.