我安装了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 %>
答案 0 :(得分:2)
首先,我创建了一个搜索表单,请求索引操作(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
就是这样。