Search in Rails

后端 未结 3 534

I have a table of \"posts\" with attributes that include title and body.

posts_controller.rb:

class PostsController < A         


        
相关标签:
3条回答
  • 2020-12-07 17:28

    Although this is not a direct answer to your question, here are some resources that may help you as you are learning about search and getting it implemented in your Rails app.

    A Simple search form

    Advanced search form

    Searching with AJAX

    Powerful search functionality with the Sunspot gem

    List of the most popular search tools for Ruby

    ---------------UPDATE----------------

    Elasticsearch has been growing in popularity due to some modern awesomeness that it has, such as instant indexing. It has a ruby gem named tire. Definitely worth a look.

    Elasticsearch

    Tire

    ---------------UPDATE 2----------------

    Tire has been retired, and has been replaced by Elasticsearch-ruby

    0 讨论(0)
  • 2020-12-07 17:40

    Elasticsearch with gem searchkick

    note: searchkick is also contributed by tire) makes you more comfortable to work on.

    For more refer:

    SearchKick

    0 讨论(0)
  • 2020-12-07 17:40

    For people coming here and looking for a solution in Rails 4, try the following example:

    Posts Controller:

    class PostsController < ApplicationController
      def index
        if params[:search]
          @posts = Post.search(params[:search]).order("created_at DESC")
        else
          @posts = Post.all.order('created_at DESC')
        end
      end
    end
    

    Post Model:

    def self.search(search)
      # Title is for the above case, the OP incorrectly had 'name'
      where("title LIKE ?", "%#{search}%")
    end
    

    The index.html.erb remains the same apart from the search form:

    <%= form_tag(posts_path, :method => "get", id: "search-form") do %>
      <%= text_field_tag :search, params[:search], placeholder: "Search Posts" %>
      <%= submit_tag "Search" %>
    <% end %>
    

    Note that the paths, controllers and columns you are using may be different.

    0 讨论(0)
提交回复
热议问题