TLDR - Basic search field with Ruby on Rails
Yaroslav Shmarov

Yaroslav Shmarov @superails

About: I write about different Ruby on Rails topics. Check it out!

Location:
Chernihiv, Ukraine
Joined:
Nov 4, 2017

TLDR - Basic search field with Ruby on Rails

Publish Date: Apr 23 '21
10 4

MISSION: field to search for user email that contains characters. Example:

search-field.png

users_controller.rb

  def index
    if params[:email]
      @users = User.where('email ILIKE ?', "%#{params[:email]}%").order(created_at: :desc) #case-insensitive
    else
      @users = User.all.order(created_at: :desc)
    end
  end

Enter fullscreen mode Exit fullscreen mode

any view (users/index.html.haml or in a bootstrap navbar)

.form-inline.my-2.my-lg-0
  = form_tag(courses_path, method: :get) do
    .input-group
      = text_field_tag :title, params[:title], autocomplete: 'off', placeholder: "Find a course", class: 'form-control-sm'
      %span.input-group-append
        %button.btn.btn-primary.btn-sm{:type => "submit"}
          %span.fa.fa-search{"aria-hidden" => "true"}

Enter fullscreen mode Exit fullscreen mode

.html.erb without bootstrap

<%= form_tag(users_path, method: :get) do %>
  <%= text_field_tag :email, params[:email], autocomplete: 'off', placeholder: "user email" %>
  <%= submit_tag "Search" %>
<% end %>

Enter fullscreen mode Exit fullscreen mode

That's it! Looks nice, doesn't it?

Comments 4 total

  • Oliver
    OliverApr 23, 2021

    What's the markup in the second example? It doesn't look like erb or HTML.

    • Yaroslav Shmarov
      Yaroslav ShmarovApr 23, 2021

      Good that you mentioned! I've updated the post to mention that it's HAML.

  • Oliver
    OliverApr 23, 2021

    I'm a bit rusty so need reminding. Is User.where('email ILIKE ?', "%#{params[:email]}%") safe from injection attack?

    • Daniel Uber
      Daniel UberApr 23, 2021

      I believe the SQL sanitation happens when you use a positional variable ? rather than the (more obvious) direct string interpolation:

            @users = User.where("email ILIKE \"%#{params[:email]}%\"").order(created_at: :desc) # unsafe/unsanitized
      
      Enter fullscreen mode Exit fullscreen mode

      A little unsure on how/where that's happening, but it might be happening in the calls to sanitize_sql in build_where_clause and related query builder steps apidock.com/rails/v6.1.3.1/ActiveR...

      It's documented in the security guide, guides.rubyonrails.org/security.ht... and in the query guide guides.rubyonrails.org/active_reco... and the "don't build strings yourself" bad example is more or less the same as above.

Add comment