开发者

How to implement simple search form to be used in conjunction with paginate?

开发者 https://www.devze.com 2023-04-02 13:09 出处:网络
I am following Ryan Bates\' railcasts: http://railscasts.com/episodes/37-simple-search-form in solving my issue with the search results on a page with will-paginate.

I am following Ryan Bates' railcasts: http://railscasts.com/episodes/37-simple-search-form in solving my issue with the search results on a page with will-paginate.

Here he answers the question as to how to solve this problem. However, I've tried them and haven't had any luck. From following his second resolution, I get a NoMethod error for "search_conditions" as the result.

The Code:

    projects/index.rhtml 
<% form_tag projects_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

projects_controller.rb 
def index
  @projects = Project.search(params[:search])
end

models/project.rb 
def self.search(search)
  if search
    find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end

H开发者_运维问答is Answers:

One way is to call the class method "search_conditions" and instead of having it do the find it will just return a conditions array so you could use it in the paginate method.

Course.paginate(:all, :conditions => Course.search_conditions(..))

Another is to call the method "paginated_search" and have it call "paginate" instead of "find".

Lastly you could have the search method accept a block which uses with_scope to set the find conditions. This way you could call "paginate" in that block and the conditions will automatically be applied.

Can someone explain to me how I should go about solving this? I am new to rails and maybe I am just misunderstanding what he is saying.


Railscast you following is pretty old, lots changed since then. Try to change implementation of search method like this:

def self.search(search)
  if search
    where 'name LIKE ?', "%#{search}%"
  else
    scoped
  end
end

and something like this in controller:

def index
  @projects = Project.search(params[:search]).paginate(:page => params[:page])
end
0

精彩评论

暂无评论...
验证码 换一张
取 消