【问题标题】:Ruby on rails - pagination on search resultRuby on rails - 搜索结果分页
【发布时间】:2013-12-23 20:14:34
【问题描述】:

我有 2 个模型,Post 和 Location,其中 location has_many posts 和 post belongs_to location。搜索工作正常,分页工作也很好,除了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 %>

控制器 post_controller.rb:

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

模型帖子.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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 当我点击第2页时,url显示: .../search?company=&location_id=&page=2&title=&utf8=%E2%9C%93 ,页面显示第1页结果。 ..为什么会这样?
    • 我认为问题出在这个地方: :page => @page 。变量@page 来自哪里?您可能应该在调用 Post 类的 search 方法时发送此变量。
    • 在模型中:def self.search(title, company, location_id, page) ... :page => page, ... end。在控制器中: def search ... page = params[:page]; @posts = Post.search(title, company, location_id, page);结束
    • 谢谢你!还有一件事要问,我想限制显示的搜索结果的数量。我的代码在条件中有 .last(200),但似乎无法正常工作,因为它仍然显示所有结果。
    • 尝试 order("id desc").limit(200) 而不是 last(200)。如果有帮助,请给我您使用 last 方法的代码字符串
    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2012-07-23
    • 2015-08-13
    • 2012-09-30
    • 1970-01-01
    • 2015-04-20
    • 2015-07-19
    相关资源
    最近更新 更多