开发者

Rails 3: sunspot solr : adding search ability for every page

开发者 https://www.devze.com 2023-03-06 11:48 出处:网络
How do you add search to a layout so it can search for posts through every page of the site? such as here on stackoverflow.

How do you add search to a layout so it can search for posts through every page of the site? such as here on stackoverflow.

Tutorials show adding the search method to the index action of the PostsController, and then adding the form and results block in views/post/index.html.erb.

I've been trying to create a form in application.html.erb that sends a get request to the search action of the posts controller. I can't seem to get it right, can someone help explain where I'm going wrong?

Currently I'm getting this error when going to my homepage:

NameError in Pages#home

undefined local variable or method `search_posts_path'

PostsController

   def search
     if params[:q]
       query = params[:q]
       @search = Post.search do
         keywords query
       end
       @posts = @search.results
     end
    end

post model

 searchable do
       text :title, :default_boost => 2
       text :content
  end

routes.rb

  match 'auth/:provider/callback' => 'authentications#create'
  resources :authentications

  devise_for :users, :controllers => {:registrations => 'registrations'}




  resources :posts do
      member do
      get :likers, :search
      end
  end  

  resources :relationships, :only => [:create, :destroy]
  resources :appreciations, :only => [:create, :destroy]

  root :to => "pages#home"

 match '/contact', :to => 'pages#contact'
 match '/about',   :to => 'pages#about'
 match '/help',    :to => 'pages#help'
 match '/blog',    :to => 'pages#blog'


  resources :users do
     member do
     get :following, :followers, :lik开发者_C百科es
     end
     resources :collections
  end

views/layouts/application.html.erb

<%= form_tag search_posts_path, :method => :get do %>
<p>
<%= text_field_tag :q, params[:q] %> <%= submit_tag "Search!" %>
</p>
<% end %>

PagesController

 def home
    @title = "Home"
    if user_signed_in?
      @user = current_user
      @post = current_user.posts.build
      @feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
    else
     #render :layout => 'special_layout' 
    end
  end


This is a Ruby on Rails routing question.

The member route is for operating on a single record. So you are defining search_post_path(@post) which will route to something like /posts/1/search

What you want is a collection route.

resources :posts do
  member do
    get :likers
  end
  collection do
    get :search
  end
end

This will create the search_posts_path method and route to /posts/search as you are expecting.

See also: http://guides.rubyonrails.org/routing.html#adding-more-restful-actions

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号