Ralf17 Ralf17 - 1 month ago 11
Ruby Question

Search Form in Rails

I'm trying to add a search form for my list of users which was authenticated by Devise. I am also using Will Paginate gem and have watched the video in RailsCast. The following are the contents of some of my files:

routes.rb:

Rails.application.routes.draw do
get 'users/list'
root 'static_pages#home'

devise_for :users

devise_scope :user do
get '/signup', to: 'devise/registrations#new'
get '/login', to: 'devise/sessions#new'
get '/signout', to: 'devise/sessions#destroy'
end

get 'static_pages/about'
get 'static_pages/faqs'
get 'static_pages/contact'

# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end


user_controller.rb:

class UsersController < ApplicationController
def list
@users = User.search(params[:search], params[:page])
end
end


list.html.erb:

<h1>List of Users</h1>
<% form_tag users_list_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>

<% for user in @users %>
<p>ID: <%= user.id %></p>
<p>Username: <%= user.username %></p>
<p>Email: <%= user.email %></p>
<p>Name: <%= user.name %></p>
<% end %>

<%= will_paginate @users %>


user.rb:

class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:authentication_keys => [:login]


def self.search(search, page)
paginate :per_page => 5, :page => page,
:conditions => ['name like ?', "%#{search}%"],
:order => 'name'
end

def login=(login)
@login = login
end
def login
@login || self.username || self.email
end

def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
if conditions[:username].nil?
where(conditions).first
else
where(username: conditions[:username]).first
end
end
end
end


However, I am getting an error:

enter image description here

Answer

Conditions are part of query not pagination. They should be in ActiveRecord methods as well as order:

def self.search(search, page)
  where(['name like ?', "%#{search}%"])
  .paginate(per_page: 5, page: page),
  .order('name')
end