How can I send a search query(URL params) using text_field in Rails 5?

Viewed 969

In Task controller (action index) I have this line:

@tasks = Task.where("title LIKE '%#{params[:q]}%'")

In view I have form_tag like this:

= form_tag tasks_path(format: :js), method: :get do |f|
  = text_field_tag :q, params[:q]
  = submit_tag :Search

And it is works fine, output in terminal:

Started GET "/tasks.js?utf8=%E2%9C%93&q=example&commit=Search" for 127.0.0.1 at 2018-11-08 10:28:37 +0200
Processing by TasksController#index as JS
  Parameters: {"utf8"=>"✓", "q"=>"example", "commit"=>"Search"}
  Rendering welcome/index.html.haml
  Task Load (0.4ms)  SELECT "tasks".* FROM "tasks" WHERE (title LIKE '%example%')

But I need to use form_for not form_tag. My form_for form:

= form_for tasks_path, method: :get, remote: true do |f|
  = f.text_field :q, value: params[:q]
  = f.submit :Search

Terminal output:

Started GET "/index?utf8=%E2%9C%93&%2Ftasks%5Bq%5D=fdvdfvdfv&commit=Search" for 127.0.0.1 at 2018-11-08 10:30:11 +0200
Processing by WelcomeController#index as JS
  Parameters: {"utf8"=>"✓", "/tasks"=>{"q"=>"fdvdfvdfv"}, "commit"=>"Search"}
  Rendering welcome/index.html.haml within layouts/application
  Task Load (0.4ms)  SELECT "tasks".* FROM "tasks" WHERE (title LIKE '%%')

And it is don't work, empty between '%%'. Maybe you can help me.

2 Answers

You should use form_tag not form_for. form_for is used to create a form for a model object, which isn't your case.

And to answer your question, when you look at the generated params in the log, you have "/tasks"=>{"q"=>"fdvdfvdfv"}. so params[:q] won't work in this case.

My final answer, go with form_tag.

In Rails 5.1+ you should use form_with which replaces both form_for and form_tag.

Without a model

= form_with(url: tasks_path(format: :js), method: :get) do |f|
  = f.text_field :q, value: params[:q]
  = f.submit :Search

Make sure you parameterize the SQL query to avoid a SQL injection vulnerability:

@tasks = Task.where("title LIKE ?", "%#{params[:q]}%")

Virtual model

Or you can create a virtual model, which is a model without a database table:

# app/models/seach_query.rb
class SearchQuery
  include ActiveModel::Model
  attr_accessor :q
end

= form_with(model: (@search_query || SearchQuery.new) url: tasks_path(format: :js), method: :get) do |f|
  = f.text_field :q
  = f.submit :Search

class TasksController < ApplicationController
  # ...
  def index
    @tasks = Task.all
    if params[:search_query]
      @search_query = SearchQuery.new(params.fetch(:search_query).permit(:q))
      @tasks = @tasks.where('tasks.title LIKE ?', "%#{ @search_query.q }%")
    end
  end
end

The advantage of a virtual model is that you can use validations, localize fields with the I18n module etc and organize your code.

Related