Ruby on rails 如何在表单中保存参数?
对于我的搜索表单,我使用以下解决方案: 我的搜索页面看起来像:Ruby on rails 如何在表单中保存参数?,ruby-on-rails,Ruby On Rails,对于我的搜索表单,我使用以下解决方案: 我的搜索页面看起来像: = simple_form_for search_query, :url => :search, do |f| = f.input :first_name = f.input :last_name ... Table To Display Results is here 在我的控制器中,我有: def search search_params = params[:search_query]
= simple_form_for search_query, :url => :search, do |f|
= f.input :first_name
= f.input :last_name
...
Table To Display Results is here
在我的控制器中,我有:
def search
search_params = params[:search_query]
@people = Result of some searching
end
上面的代码是有效的,只是用户看不到他们刚刚在表单中输入的值,只能得到结果。表单再次呈现,现在为空
我尝试的解决方案是:
def search
search_params = params[:search_query]
@people = Result of some searching
@search_query = params[:search_query]
end
然而,现在表单在
=f行抛出了一个NoMethodError
和未定义的方法'first\u name',我想这里的诀窍是使用GET而不是POST,这样那些搜索参数就可以在您的视图中保持可见
下面是一个直接来自我编写的一个工作应用程序的示例
def index
authorize! :index, Employee
params[:filter] ||= 'All' # Default to All Employees
params[:search] ||= '' # Default to blank
page_title ||= params[:filter].titleize
# Clear the search field if a filter option was selected
if session[:employee_filter] != params[:filter]
session[:employee_filter] = params[:filter]
params[:search] = ''
end
# Generate an array of our filter elements (include all departments)
@page_links = %w[All Featured Admins]
Department.all.each do |department|
@page_links << [department.title, department.name]
end
# Check and execute the filter option (defaults to All above)
case params[:filter]
when 'All'
@employees = Employee.search(params[:search]).by_name.page(params[:page]).per(15)
when 'Featured'
# We need this to be all on one page so that we can drag-and-drop position employees
@employees = Employee.search(params[:search]).is_featured.page(params[:page]).per(99999)
when 'Admins'
@employees = Employee.search(params[:search]).admins.by_name.page(params[:page]).per(15)
@page_title = 'Site Administrators'
else
@employees = Employee.search(params[:search]).dept(params[:filter]).by_index.page(params[:page]).per(15)
end
@page_title ||= "#{page_title} Employees"
@page_title = "'#{params[:search]}' in #{page_title}" unless params[:search].blank?
end
最后是索引中的搜索表单(HAML格式):
它有一些额外的搜索内容(比如额外的过滤器),所以让我知道这对你来说太复杂了
def self.search(search)
if search
results = where('last_name ILIKE ? OR first_name ILIKE ? OR email ILIKE ?', "%#{search}%", "%#{search}%", "%#{search}%")
results = where('title ILIKE ?', "%#{search}%") if results.blank?
results = joins(:location).where('locations.name ILIKE ?', "%#{search}%") if results.blank?
return results
end
end
.sort-index
= form_tag admin_employees_path, method: 'get' do
= select_tag :filter, options_for_select(@page_links, params[:filter]), onchange: "this.form.submit();"
%br
= text_field_tag :search, params[:search], placeholder: 'Search Name, Title, or Location', size: 35
= submit_tag :search, name: nil, hidden: true