Rails渲染搜索栏太阳黑子搜索

时间:2014-04-26 01:09:10

标签: ruby-on-rails search ruby-on-rails-4 render sunspot

我正在使用相同视图的方法并使用渲染,它一切正常,但搜索仍然基于索引方法而不是我的其他方法。我是否必须为其他方法创建一个完整的新视图才能使其单独工作?

示例:

在我的控制器中我有:

 def index

  @search = Post.search do #Post.search do
  fulltext params[:search]
  paginate :page => params[:page], :per_page => 20 
  order_by(:updated_at, :desc)
   end
   @posts = @search.results 
 end



 def local

  @search = Post.search do #Post.search do
  fulltext params[:search]
  with(:school, current_user.school)
  facet(:school)
  paginate :page => params[:page], :per_page => 20 
  order_by(:updated_at, :desc)
  end
   @posts = @search.results

   render :index  
end

如果我翻转方法并使索引成为本地,反之亦然,那么当我搜索时,搜索过滤结果基于:school,但代码的方式,我有一个指向本地操作的链接,一切都被过滤但是当我搜索时,无论学校领域如何,我都会得到结果

除了必须复制我的index.html.erb并将其更改为local.html.erb

之外,还有一个更好的解决方案。

谢谢!

1 个答案:

答案 0 :(得分:0)

解决方案:

好的,所以我将本地方法的参数重命名为本地搜索,如下所示:

def local

  @search = Post.search do #Post.search do
  fulltext params[:localsearch]                   #changed from 'search' to localsearch'
  with(:school, current_user.school)
  facet(:school)
  paginate :page => params[:page], :per_page => 20 
  order_by(:updated_at, :desc)
 end
 @posts = @search.results

 render :index  
end

然后在视图application.html.erb中我添加了if语句:

    <% if current_page?(posts_path) %>
      <div class="pull-left" style="display: inline-block;"> <div role="search">      
      <%= form_tag posts_path, :method => :get do %>
      <%= text_field_tag :search, params[:search], id: 'search' , autofocus: false ,:placeholder => "search",:class =>'fruute-input', :size => 30 %>
        </div>
        <button type="submit" id="mybutton" >
          <i class="fa fa-search fa-lg" style = "color: white;"></i>                     
        </button>
        <% end %>
        <% end %>

     <% if current_page?(index_path) %>
      <div class="pull-left" style="display: inline-block;"> <div role="search">      
      <%= form_tag index_path, :method => :get do %>
        #in this next line I pass :localsearch to local method;
      <%= text_field_tag :search, params[:localsearch], id: 'search' , autofocus: false ,:placeholder => "search",:class =>'fruute-input', :size => 30 %>  
        </div>
        <button type="submit" id="mybutton" >
          <i class="fa fa-search fa-lg" style = "color: white;"></i>                     
        </button>
        <% end %>
        <% end %>

对于那些希望将其与太阳黑子一起使用的人来说:

在模型中:

  validates :price, :numericality => {:only_integer => true}
  searchable do
    text :title
    text :author 
    text :course
    text :school
    text :email
    text :description
    text :price
    integer :id
    time :updated_at


string :school #notice, facet fields must be string, just add the field from above and diplicate it as string if text

<强> BAM!