【问题标题】:How to set up search with will_paginate?如何使用 will_paginate 设置搜索?
【发布时间】:2023-03-10 09:48:01
【问题描述】:

我安装了will_paginate 并在posts_controller 索引def 中写入:

@posts = Post.paginate(:page => params[:page], :per_page => 10, :order => 'id DESC', :conditions => ['title like ?', "%#{params[:search]}%"])

但是搜索不起作用。当我点击搜索按钮时,它会将 url 更改为:

http://178.62.xxx.xxx/find/?utf8=%E2%9C%93&search=the

页面中的帖子保持不变。

路线:

get "/find/" => "posts#index"

后模型:

def self.search(query)
where("title like :title", title: "%#{query.strip.chomp}%")

结束

在 index.html.erb 中:

<%= form_tag('/find/', :method => "get", id: "search-form") do %>
     <%= text_field_tag :search, params[:search], placeholder: "Найти посты", :class => "search" %>
      <%= submit_tag "OK", :name => nil, :class => "search_btn" %>
<% end %>

【问题讨论】:

    标签: ruby-on-rails search will-paginate


    【解决方案1】:

    我解决了。

    首先,我创建了请求索引操作的搜索表单 (GET /posts)。

    # index.html.erb - Search Form
    <%= form_tag posts_path, method: :get do %>
      <%= text_field_tag :search, "" %>
      <%= submit_tag 'Search' %>
    <% end %>
    

    接下来,我定义了索引操作。

    # Controller
    def index
      # params = { :search => 'search keywords ...' }
      @products = Product.search(params).paginate(:page => params[:page], :per_page => 2)
    end
    

    然后,定义Post#search

    paginate 方法仅用于ActiveRecord::Relation。 所以,Post#search 必须返回 ActiveRecord::Relation

    def self.search(params)
      products = all # for not existing params args
      products = products.where("name like ?", "%#{params[:search]}%") if params[:search]
      products
    end
    

    就是这样。

    【讨论】:

    • no implicit conversion of Symbol into Integer 此处出错
    • 对我来说工作得很好,除了 'all' 返回 Array 而不是 Relation。使用 Products.order('name') 代替。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2011-02-01
    • 1970-01-01
    相关资源
    最近更新 更多