我使用form_tag
创建了一个简单的搜索表单,并且我有一个gem will_paginate
。当我尝试搜索某些内容时,会出现错误:undefined method 'total_pages' for #<Post::ActiveRecord_Relation:0x007f91ca043130>
这是我的post_controller.rb的一部分:
def index
@posts = unless params[:search].nil?
Post.search(params[:search])
else
@posts = Post.paginate(page: params[:page], :per_page => 5)
end
end
模型post.rb:
class Post < ActiveRecord::Base
belongs_to :user
default_scope -> {order('created_at DESC')}
validates :user, presence: true
validates_presence_of :title, :body, :tags
validates :title, length: { in: 5..100}
validates :tags, uniqueness: true
validates :user_id, presence: true
def self.search(search)
where("title LIKE ? OR body LIKE ?", "%#{search}%", "%#{search}%")
end
end
并查看posts_index:
<%= form_tag(posts_path, method: 'GET') do%>
<%= text_field_tag :search, params[:search], class: 'input-sm',placeholder: 'Search for...'%>
<%= image_submit_tag('search.png', class: 'picture_size')%>
<% end %>
<%= will_paginate %>
<% @posts.each do |post| %>
<p> <%= post.title %> </p>
<p><%= post.body %> </p>
<p> <%= post.tags %> </p>
<% end %>
<% will_paginate %>
它仍然可以正常工作,除非我尝试搜索某些东西。只有在搜索后才收到错误。我该如何解决这个问题?