ruby-on-rails - 如何使用 will_paginate 设置搜索?

标签 ruby-on-rails search will-paginate

我已经安装了 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 %>

最佳答案

我解决了。

首先,我创建了请求索引操作的搜索表单(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

仅此而已。

关于ruby-on-rails - 如何使用 will_paginate 设置搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345153/

相关文章:

python - 将搜索方法转换为搜索字符串列表

javascript - 在网页中搜索数千个关键字的最快方法

ruby-on-rails - 自定义 will_paginate 渲染器

html - 导轨 3 : How do you style will_paginate links?

mysql - 选择所有具有非空关联记录的记录

ruby-on-rails - 带有 Amazon S3 的 Active Storage 不使用指定的文件名保存,而是使用文件 key 保存

sql - Rails PG::UndefinedTable:错误:缺少表的 FROM 子句条目

php - 如果搜索结果不存在则隐藏表

mysql - Rails4、MySql、mysql2 编码问题

ruby-on-rails - 如何让 Rails View 处理来自数据库内容的 HTML 标签?