Using will_paginate while applying a scope with params to the Model

亡梦爱人 提交于 2019-12-25 07:14:10

问题


I am attempting to create a search box that can be used to search User's by their name. The problem I am running into is that I also want to use the will_paginate gem. This line of code @users = User.name(params[:name]).paginate(page: params[:page]) if params[:name].present? is where I think the problem lies.

class UsersController < ApplicationController

def index
  @users = User.all.paginate(page: params[:page])
  @users = User.name(params[:name]).paginate(page: params[:page]) if params[:name].present? 
end 

class User < ActiveRecord::Base
  scope :name, -> (name) { where("name ILIKE ?", "%#{name}%")} 
end

users/index.html.erb

  <%= form_tag users_path, method: :get do %>
    <%= text_field_tag :name, params[:name], :placeholder => "Search by name" %>
    <%= submit_tag "Search"%>
  <% end %>

回答1:


You have a space in line one of your controller file. The super class has a space in it "Application Controller"

That would cause a boot time H10 error on Heroku.




回答2:


:name cannot be used as the scope. When I changed it to :namesearch the code worked.

class User < ActiveRecord::Base
  scope :nameseach, -> (name) { where("name ILIKE ?", "%#{name}%")} 
end

def index
  @users = User.all.paginate(page: params[:page])
  @users = User.namesearch(params[:name]).paginate(page: params[:page]) if params[:name].present? 
end 


来源:https://stackoverflow.com/questions/38130833/using-will-paginate-while-applying-a-scope-with-params-to-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!