Rails 搜索功能 [英] Rails search functionality

查看:54
本文介绍了Rails 搜索功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的大学参加 Rails 课程,我正在尝试创建一个搜索表单,该表单将在同一页面上显示结果,而不是显示不同的结果页面.这是一件很简单的事情吗?我正在为每个博物馆创建一个包含文物的博物馆应用,但我希望用户从任一页面搜索文物.

I am taking a rails class at my University and I am trying to create a search form which will show the results on the same page rather than show a different page of results. Is this something simple to do? I am creating a museum app with artifacts for each museum but I want the user to search artifacts from either page.

在我的 routes.rb 上

On my routes.rb I have

resources :artifacts do
    collection do
        get 'search'
    end
  end

在我的博物馆索引中,我有他给我们的代码,但不确定如何调整同一页面的获取路线.

On my museum index I have the code below that he gave us but not sure how to tweak the get routes for the same page.

<%= form_tag search_artifacts_path, :method => 'get' do %>

    <p>
    <%= text_field_tag :search_text, params[:search_text] %>
    <%= submit_tag 'Search' %>
    </p>

<% end %>

<% if @artifacts %>
    <p> <%= @artifacts.length %> matching artifacts. </p>

    <h2> Matching Artifacts </h2>
    <% @artifacts.each do |a| %>

        <%= link_to "#{a.name} (#{a.year})", a %><br />

    <% end %>

<% end %>

推荐答案

是的,这很容易.如果 params[:search_text] 存在,只需让索引页面返回搜索结果 - 这样您就不需要新的路由或不同的页面.

Yes, this is easy. Just have the index page return the search results if params[:search_text] is present - this way you don't need a new route or a different page.

class ArtifactsController < ApplicationController
  def index
    @artifacts = Artifact.search(params[:search_text])
  end    
end

class Artifact < ActiveRecord::Base
  def self.search(query)
    if query
      where('name ILIKE ?', "%#{query}%")
    else
      all
    end
  end
end

那么你的表单看起来像:

So then your form looks like:

<%= form_tag artifacts_path, :method => 'get' do %>
  <p>
   <%= text_field_tag :search_text, params[:search_text] %>
   <%= submit_tag 'Search' %>
  </p>
<% end %>

所以你真正想要做的是你想要搜索的任何页面,包括一个向同一页面发出请求的表单.

So what you really want to do is any page you want to search, include a form which makes a request to that same page.

然后在每个控制器方法中放入这行代码:

Then in each of those controller methods just put this line of code:

    @artifacts = Artifact.search(params[:search_text])

这将仅使用与搜索查询匹配的工件填充 @artifcats 数组.

and that will populate the @artifcats array with only artifacts that match the search query.

这篇关于Rails 搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆