Rails 3 Ajax Search

2020-08-05 10:54发布

I'm following the railscasts rails ajax tutorial and geting into some trouble, am i missing something or is the tutorial only meant to be covered for pre rails 3.1?

controller:

def index

    @notes = Note.search(params[:search])


end

Model:

class Note < ActiveRecord::Base

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


end

View:

<%= form_tag notes_path, :method => 'get', :id => "notes_search" do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
  <div id="notes"><%= render 'notes' %></div>
<% end %>

Coffescript file:

jQuery ->
  # Ajax sorting and pagination on click
  $('#notes td.sortable a, #notes .pagination a').live('click', ->
    $.getScript(this.href)
    false
  )
  # Ajax search on submit
  $('#notes_search').submit( ->
    $.get(this.action, $(this).serialize(), null, 'script')
    false
  )
  # Ajax search on keyup
  $('#products_search input').keyup( ->
    $.get($("#notes_search").attr("action"), $("#notes_search").serialize(), null, 'script')
    false
  )

Error is on this line:

ActionView::MissingTemplate in Notes#index

   <div id="notes"><%= render 'notes' %></div>

2条回答
▲ chillily
2楼-- · 2020-08-05 11:12

The ActionView::MissingTemplate exception basically says that there is no view file for the action you're trying to render.

You need to have a partial view called "_notes.html.erb" for it to work. Inside the view you should have something like that:

<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<%= will_paginate @notes %>

I took that code from the tutorial you're referring to http://railscasts.com/episodes/240-search-sort-paginate-with-ajax, maybe you don't have those params or don't have will_paginate gem installed yet, adjust it to your needs.

查看更多
老娘就宠你
3楼-- · 2020-08-05 11:13

This totally irrelevant to the tutorial but why don't you consider using datatables. Does the same thing as the railscasts tutorial and also has full documentation and API to make it fully customizable.

查看更多
登录 后发表回答