Search in Rails

后端 未结 3 539

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

posts_controller.rb:

class PostsController < A         


        
3条回答
  •  清歌不尽
    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.

提交回复
热议问题