【问题标题】:Using search function in rails to retrieve a result and display it first in the index page在rails中使用搜索功能检索结果并首先在索引页面中显示
【发布时间】:2014-10-13 15:16:20
【问题描述】:

我正在尝试在我的 rails 应用程序中实现搜索功能,我首先在 index.html.erb 视图上搜索并显示特定的搜索结果。目前我有一个搜索功能正在工作,它会在索引页面上自行返回特定项目。

理想情况下,我希望先显示此项目,然后再将所有其他项目显示在下方。

我的代码如下:

品牌.rb

 def self.search(query)
    where("author like ?", "%#{query}%")
  end

brand_controller.rb

      def index
    if params[:search]
      @brand = Brand.search(params[:search]).order("created_at DESC")
    else
      @brand = Brand.all.order(':date')
    end
  end

我知道 where 方法将值作为数组返回,所以我可能会使用 array.first 来首先输出这个结果,但是有没有更简单的方法来输出我想要的视图。谢谢!

【问题讨论】:

    标签: ruby-on-rails search view


    【解决方案1】:

    结果证明这是一个非常简单的解决方案,我责怪星期一。

    我所要做的就是为我的搜索创建另一个变量并首先迭代该结果,然后迭代其余项目。

    在我的控制器中

     def index
          @brand = Brand.order('created_at DESC')
          if params[:search]
            @brand = Brand.search(params[:search]).order("author DESC")
            @other = Brand.search_all(params[:search]).order("author DESC")
          else
            @brand = Brand.all.order('author DESC')
          end
      end
    

    在我的模型中

      def self.search(query)
          where("author like ?", "%#{query}%")
      end
    
      def self.search_all(query)
        where("author not like ?", "%#{query}%")
      end
    

    最后在我看来

     <% if @brand.any? %>
    
                          <% @brand.in_groups_of(2) do |group| %>
                              <% group.each do |brand| %>
                                  <% if brand %>
    
                                          <h4> <%= brand.author %></h4>
                                          <a href="<%=brand_path(brand)%>">
                                            <%=image_tag brand.brand_logo, class: 'img-rounded', :"data-uid" => brand.uid %>  </a>
    
                                  <% end %>
                              <% end %>
                          <% end %>
                  <% end %>
    
    
    
    
    
                      <% if @other %>
    
                          <% @other.in_groups_of(2) do |group| %>
    
                              <% group.each do |other| %>
                                  <% if other %>
                                          <h4> <%= other.author%></h4>
                                          <a href="<%=brand_path(other)%>">
                                            <%=image_tag other.brand_logo %>  </a>
                                  <% end %>
                              <% end %>
                          <% end %>
                      <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多