Ruby on rails - pagination on search result

爷,独闯天下 提交于 2019-12-30 13:54:49

问题


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

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

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:


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

I mean :per_page can't be larger than :total_entries



来源:https://stackoverflow.com/questions/20424562/ruby-on-rails-pagination-on-search-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!