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