父.rb
class Parent
include Mongoid::Document
field :name, type: String
field :hobby, type: String
field :born, type: Date
has_many :children
accepts_nested_attributes_for :children
def self.search(search)
if search
any_of({name: search}, {hobby: search})
end
end
end
孩子.rb:
class Child
include Mongoid::Document
field :name, type: String
field :hobby, type: String
field :born, type: Date
belongs_to :parent
end
parents_controller.rb
class ParentsController < ApplicationController
before_action :set_parent, only: [:show, :edit, :update, :destroy]
# GET /parents
# GET /parents.json
def index
if params[:search].empty?
@parents = Parent.all
else
@parents = Parent.search(params[:search])
end
end
# GET /parents/1
# GET /parents/1.json
def show
end
# GET /parents/new
def new
@parent = Parent.new
end
# GET /parents/1/edit
def edit
end
# POST /parents
# POST /parents.json
def create
@parent = Parent.new(parent_params)
respond_to do |format|
if @parent.save
format.html { redirect_to @parent, notice: 'Parent was successfully created.' }
format.json { render action: 'show', status: :created, location: @parent }
else
format.html { render action: 'new' }
format.json { render json: @parent.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /parents/1
# PATCH/PUT /parents/1.json
def update
respond_to do |format|
if @parent.update_attributes(parent_params)
format.html { redirect_to @parent, notice: 'Parent was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @parent.errors, status: :unprocessable_entity }
end
end
end
# DELETE /parents/1
# DELETE /parents/1.json
def destroy
@parent.destroy
respond_to do |format|
format.html { redirect_to parents_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_parent
@parent = Parent.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def parent_params
params.require(:parent).permit(:name, :hobby, :born)
end
end
在产品的 index.html.erb 中搜索标签
<%= form_tag parents_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
问题:
- 当我有 2 个名字时:Alex 和 Alex Jr.,当我搜索“Alex”时,它只给了我一个结果。但我希望“Alex Jr”也能作为搜索结果。
- 我的搜索区分大小写。我想忽略这一点。
- 我希望不仅能够在主文档中搜索,而且能够在所有级别的嵌套文档中进行搜索。在这种情况下,我将主文档作为模型 parent.rb 并嵌套一个名为 child.rb 的文档。因此,例如,当我搜索姓名时,我不仅要搜索父母的姓名,还要搜索他的孩子。
- 我想通过指定日期范围来添加搜索功能。例如,要查找从 A 日期到 B 日期出生的所有记录。