在Rails中搜索表单

时间:2016-10-13 23:39:12

标签: ruby-on-rails ruby devise will-paginate

我正在尝试为我的用户列表添加一个搜索表单,该表单由Devise进行身份验证。我也在使用Will Paginate gem,并在RailsCast观看了视频。以下是我的一些文件的内容:

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

然而,我收到一个错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

条件是查询不是分页的一部分。它们应该采用ActiveRecord方法以及订单:

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