Advanced Search Form in Rails 5


This article will only focus on the changes that is required to get the railscasts episode 111 Advanced Search Form working with Rails 5.

Rails 5 Changes

Create a new rails project, model and controllers.

rails new searchly
rails g model product name category:references price:decimal released_at:date
rails g model category name
rails g model search keywords category:references min_price:decimal max_price:decimal
rails g controller products index
rails g controller searches

Migrate and populate the database.

rails db:migrate
rails db:seed

The syntax in Rails 5 for ActiveRecord has been changed for:


New syntax:

Category.find_or_create_by(name: 'Toys')

So the seeds.rb has:

Product.create!(category: Category.find_or_create_by(name: "Toys & Games"), name: "Settlers of Catan", price: 34.99, released_at: "2011-07-15")

The searches controller has a private method that allows all the search attributes to be submitted.

def allowed_params

You don't need ||= in products method in search model because of Rails SQL caching.

def products
  @products = find_products

Creating the search model using the command shown in the beginning generates the foreign key automatically.

class CreateSearches < ActiveRecord::Migration[5.0]
  def change
    create_table :searches do |t|
      t.string :keywords
      t.references :category, foreign_key: true
      t.decimal :min_price
      t.decimal :max_price


As you can see in the schema.rb:

ActiveRecord::Schema.define(version: 20160413001116) do
  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false

  create_table "products", force: :cascade do |t|
    t.string   "name"
    t.integer  "category_id"
    t.decimal  "price"     "released_at"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  add_index "products", ["category_id"], name: "index_products_on_category_id"

  create_table "searches", force: :cascade do |t|
    t.string   "keywords"
    t.integer  "category_id"
    t.decimal  "min_price"
    t.decimal  "max_price"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  add_index "searches", ["category_id"], name: "index_searches_on_category_id"

You can download the code for this project from


In this article, you learned how to implement an advanced search form in Rails 5.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.