Ruby on Rails-搜索结果分页 [英] Ruby on rails - pagination on search result

查看:58
本文介绍了Ruby on Rails-搜索结果分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个模型,即Post和Location,其中location has_many个帖子和post includes_to location.搜索可以正常工作,分页也可以正常工作,除了total_entries之外.它显示结果中有10多个条目

I have 2 models, Post and Location, where location has_many posts and post belongs_to location. The search works fine, and the pagination works fine too except the total_entries. It shows more than 10 entries in the result

查看search.html:

View search.html:

<%= form_tag search_posts_path, :method => 'get' do %>
    <p>
        <%= text_field_tag :title, params[:title] %>
        <%= text_field_tag :company, params[:company] %>
        <%= select_tag :location_id, options_from_collection_for_select(Location.all, :id, :name, params[:location_id]), include_blank: true %>
        <%= submit_tag "Search", :name => nil %>
    </p>
<% end %>

控制器post_controller.rb:

Controller post_controller.rb:

  def search
    title = params[:title]
    company = params[:company]
    location_id = params[:location_id]
    @posts = Post.search(title, company, location_id)
  end

模型Post.rb

def self.search(title, company, location_id)
    if location_id.present?

        paginate :conditions => ['title LIKE ? AND company LIKE ? AND location_id = ?', "%#{title}%", "%#{company}%", location_id],
                        :per_page => 20,
                        :order => 'created_at DESC',
                        :page => @page,
                        :total_entries => 10

    else

        paginate :conditions => ['title LIKE ? AND company LIKE ?', "%#{title}%", "%#{company}%"],
                        :per_page => 20,
                        :order => 'created_at DESC',
                        :page => @page,
                        :total_entries => 10                
    end
end

推荐答案

参数:per_page 定义每个页面上的条目数. :total_entries 是从数据库中获取的条目总数.

The parameter :per_page defines entries count on each page. :total_entries is entries count that fetching from db in total.

我的意思是:每页不能大于:总条目

这篇关于Ruby on Rails-搜索结果分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆