Reputation: 6466
Trying to figure out Ajax search in a Rails 3 app, following this post, which itself borrows from a Railscast. Currently, when I submit, nothing happens, and if I go into the Chrome console, I see this error:
GET http://localhost:3000/search?utf8=%E2%9C%93&search=&_=1361491523102 404 (Not Found)
posts.js line 5 seems to be culpable, but that just seems to be the jQuery call, so I'm not sure what I'm doing wrong.
My relevant code:
posts.js.coffee
jQuery ->
# Ajax search on submit
$('.search_form').submit( ->
$.get(this.action, $(this).serialize(), null, 'script')
false
)
posts_controller.rb
def show
@search = Post.search(params[:search])
respond_to do |format|
format.html # show.html.erb
format.json { redirect_to @post }
end
end
def search
@search = Post.search(params[:search])
render json: { results: @search }
end
post.rb
def self.search(search)
if search
where('name LIKE ?', "%#{search}%")
else
scoped
end
end
show.html.erb
<%= form_tag search_path, method: "get", class: "search_form form-inline",
style: "display:inline-block;" do %>
<%= text_field_tag :search, params[:search], placeholder: "Search:", id: "search_field" %>
<%= submit_tag("Search", name: nil, class: "btn search", remote: true) %>
<% end %>
# Testing for @search stops it from pulling a "no method '.first' for nil NilClass" error.
<div id="list"><%= render partial: 'list', locals: { search: @search } if @search%></div>
list.html.erb
<ul>
<% @search.each do |p| %>
<li><a href=<%= p.id %> ><%= p.name %> <span class="manual_small">(<%= p.created_at.strftime("%b %d, %Y") %>)</span></a></li>
<% end %>
</ul>
Any idea what's going wrong here?
EDIT -- Adding relevant lines of routes file:
resources :posts
# ...
match '/search', to: 'posts#search'
I already had that '/search' route there. Is that right -- in which case, is the problem somewhere else? Does the rest of the code look goodish?
EDIT -- added search method to PostsController, per Damien's rec. New things of interest are a) the way I call the partial, the new search action, and that fact that then I tried to replace the contents of the show method in Post.rb with "Post.all", it still didn't show anything. No errors thrown, though.
Upvotes: 0
Views: 645
Reputation:
"No search action! Didn't realize I needed one. What should be in it? When I tried an earlier version of this without AJAX, I had a search action that was basically a replica of show (+ @search etc), with all the same variables, otherwise it wouldn't work, because it rendered the show page. Is that the right idea? It seemed very unDRY"
Using AJAX, there is no need to render the entire show
page. Just return the filtered results in desired format:
def search
@search = Post.search(params[:search])
render json: { results: @search }
end
Add format based returns if necessary.
Upvotes: 1