Ruby on rails - 搜索结果的分页

时间:2013-12-06 13:00:41

标签: ruby-on-rails ruby ruby-on-rails-3 pagination

我有2个模型,帖子和位置,其中位置has_many帖子和帖子belongs_to位置。搜索工作正常,除了total_entries之外,分页也很好。它在结果中显示了10个以上的条目

查看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 %>

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

Model 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

1 个答案:

答案 0 :(得分:1)

参数:per_page 定义每个页面上的条目数。 :total_entries 是从db中获取的条目数。

我的意思是:per_page 不能大于:total_entries