我想按名称
进行简单的用户索引搜索model user.rb
def self.search(query)
where("username LIKE ?", "%#{query}%")
end
查看用户我只有 index.html.erb
<%= form_tag users_search_path, :method => 'get' do %>
<td><%= text_field_tag :search, params[:search] %></td>
<%= submit_tag "Search", :class => "buttons buttons-rounded buttons-flat-action", :id => "button-new"%>
<br><br><br>
<% end %>
控制器
@page = params[:page]
@search = params[:search];
def index
if params[:search]
@users = User.search(params[:search]).paginate(:page => params[:page], :per_page => @page)
else
@users = User.order(:username).joins(:biography).where("`is_active?` = true AND `last_sign_in_at` > DATE_SUB(NOW(), INTERVAL 6 MONTH) ").paginate(:page => params[:page], :per_page => @page)
end
end
def search
Rails.logger.debug("event1: #{@search}")
redirect_to users_path
index
Rails.logger.debug("search start")
end
当我点击搜索按钮时,调试器信息是
D, [2014-07-09T13:10:50.755373 #5501] DEBUG -- : event1:
D, [2014-07-09T13:10:50.755508 #5501] DEBUG -- : event1:
答案 0 :(得分:0)
您的搜索方法错误,它会重定向到没有搜索参数的索引操作。您只需将表单提交到索引操作,就像这样
<%= form_tag users_path, :method => 'get' do %>
或者更优雅或许像这样
class UsersController < ApplicationController
before_action :filter_data, only: [:index, :search]
def index
end
def search
render :index
end
def filter_data
if params[:search]
@users = User.search(params[:search]).paginate(page: params[:page], per_page: params[:page])
else
@users = User.order(:username).joins(:biography).where("`is_active?` = true AND `last_sign_in_at` > DATE_SUB(NOW(), INTERVAL 6 MONTH) ").paginate(page: params[:page], per_page: params[:page])
end
end
end
希望这有帮助。