我正在尝试在单独的控制器中对模型进行复杂的搜索。我有一个学生模型。整个应用程序的首页由没有模型的单独 main_controller 处理。main_controller 及其相关的索引视图应该提供首页并显示来自多个模型的数据。
现在我想用几个不同类型的搜索条件来搜索模型。搜索标准是字符串比较、数字比较和布尔值(例如,活动,如果为真则仅显示活动学生,否则显示所有学生)。Railscast #111展示了如何基于模型和单独的搜索控制器创建这样的搜索。我创建了这样一个控制器,它工作正常。我坚持在我的主/索引中显示相关部分。
这是代码:
主/index.html.haml
- model_class = Adult
- model_class = Pupil
- model_class = MainSearch
.page-header
= render :partial => 'main_searches/form', :main_search => MainSearch.new
目前只是对表格的调用。
模型/main_search.rb
class MainSearch < ActiveRecord::Base
def pupils
@pupils ||= find_pupils
end
private
def find_pupils
pupils = Pupil.order(:name_sur)
pupils = pupils.where(id: id_search) if id_search.present?
pupils = pupils.where("name_first like ?", "%#{name_first}%") if name_first.present?
pupils = pupils.where("name_sur like ?", "%#{name_sur}%") if name_sur.present?
pupils = pupils.where(active: "true") if active == true #show only active or all
pupils
end
end
这定义了搜索。
控制器/main_searches_controller.rb
class MainSearchesController < ApplicationController
before_action :set_main_search, only: [:show, :update, :destroy]
def show
@main_search = MainSearch.find(params[:id])
end
def new
@main_search = MainSearch.new
end
def create
@main_search = MainSearch.new(main_search_params)
if @main_search.save
redirect_to root_path, notice: 'Main search was successfully created.'
else
render action: 'new'
end
end
end
如railscast中所示。
意见/main_searches/_form.html.haml
%h1 Advanced Search
= form_for :main_search, :url => main_searches_path do |f|
.field
= f.label :id_search
%br/
= f.text_field :id_search
[... ommitted some fields here ...]
.field
= f.label :active
%br/
= f.check_box :active, {}, true, false
.actions= f.submit "Search"
在新视图中渲染。
意见/main_searches/_results.html.haml
%h1 Search Results
.container-fluid
.row-fluid
.span4
%table.table{style: "table-layout:fixed"}
%thead
%tr
%th= "id"
%th= "name_sur"
%th= "name first"
%th= "a"
%div{style: "overflow-y:scroll; height: 200px"}
%table.table.table-striped{style: "table-layout:fixed"}
%tbody
- @main_search.pupils.each do |pupil|
%tr
%td= pupil.id
%td= link_to pupil.name_sur, pupil_path(pupil)
%td= pupil.name_first
%td= pupil.active
显示结果。
所以基本上一切都适用于在 railscast 中看到的一个模型。我现在需要的是让用户以某种方式处理 main_controller 中的所有内容。目前我无法将 @main_search 对象传递给 _results.html.haml 部分。我在这里想念什么?或者这甚至是进行此类搜索的正确方法吗?
提前感谢您的帮助。