繁体   English   中英

ruby on rails实现了一个搜索表单,该表单搜索多个关系

[英]ruby on rails implement a search form that searches multiple relations

我已经实现了一个简单的搜索表单(根据“简单表单”截屏视频),该表单搜索数据库中的“疾病”表。 现在,我希望使用同一搜索框来搜索“疾病”表和“症状”表。

我的代码当前如下所示:

main_page \\ index.html.erb:

<b>Illnesses</b>
    <%= form_tag illnesses_path, :method => 'get' do %>
      <p>
        <%= text_field_tag :search, params[:search] %><br/>
        <%= submit_tag "Illnesses", :name => nil %><br/>
      </p>

disorderes_controller.rb:

class IllnessesController < ApplicationController
    def index
    @illnesses = Illness.search(params[:search])

    respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @illnesses }
    end
    ...
end

disease.rb:

class Illness < ActiveRecord::Base
    ...

    def self.search(search)
    if search
        find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    else
        find(:all)
    end
 end

您能否指导我如何实现此扩展? 我是一个初学者(很明显),我真的不知道应该是什么“ form_tag”动作,我应该在哪里实现它以及哪个类应该实现扩展搜索...

谢谢李

嗯,假设您有一个类似于Illness类的Symptom类(顺便说一句,如果将搜索功能重构到一个模块中,然后在两个类中都包含此模块,那将是最干净的),那么您可以这样做:

class IllnessesController < ApplicationController
  def index
    @results = Illness.search(params[:search]) + Symptom.search(params[:search])
    ...
  end
end

但是也许您想重构控制器的名称,因为现在它不再特定于疾病。 还要注意,我们在这里使用的是两个搜索查询,而不是一个,因此它不是最佳选择,但省去了同时为两种类型的模型发送纯SQL查询的麻烦。

好的,该模块。 如果您对模块不熟悉,它们可能看起来有些怪异,但它们不过是可以在类之间共享以使事物保持DRY状态的一段代码,这也是我们的情况。 您可以想象包括模块就是从模块中获取代码并在类的上下文中对其进行评估(由解释性语言提供),其结果与将模块代码硬编码到类本身中的结果相同。 因此该模块如下所示:

module Search
  def self.search(token)
    find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
  end
end

现在,任何类,如果实现了find方法(ActiveRecord API),都可以愉快地包含此模块,并享受如下搜索功能:

require 'path/to/search'

class Foo < ActiveRecord::Base
  include Search
end

而已。 现在,如果您需要调整搜索代码,则可以在一个位置进行更改,并将其传播到所有包含者。 您还可以在有时会这样使用的模块内部创建模块:

require 'active_support/concern'

module Search
  extend ActiveSupport::Concern

  included do
    #Stuff that gets done when the module is included (new validations, callbacks etc.)
  end

  module ClassMethods
    #Here you define stuff without the self. prefix
  end

  module InstanceMethods
    #Instance methods here
  end
end

但是其中一些约定是在ActiveSupport :: Concern中定义的,因此并非所有事物都可能在纯红宝石中工作。 我鼓励您尝试这些东西,它们使红宝石真正有趣。 哦,extend非常类似于include,据我所知,它在类级别上进行评估。 因此,如果您关注我,那么包含模块的所有实例方法将成为包含程序模块的类方法。 玩得开心!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM