D
D
Danila Zaitsev2014-12-16 20:09:38
JavaScript
Danila Zaitsev, 2014-12-16 20:09:38

How to implement Ajax search in Rails?

Hello, I have the following code

<%= form_tag ads_path, :method => 'get' do %>
  <%= label_tag("Поиск по тексту:") %>
    <%= text_field_tag :search, params[:search] %>
    <br/>
  <a class="btn btn-success"><%= submit_tag 'найти', :name => nil %></a>
<% end %>

In principle, the button search works fine, you need to turn on the "live search", start searching, googling, basically everywhere they refer to the 240th episode of railscaste, but there is one problem, it uses a render bug that does not work in Assets now. Tell me how to implement now this "live search" that everyone loves?

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Viktor Vsk, 2014-12-16
@viktorvsk

render was a bug that doesn't work in Assets right now.

What it is?
If you are a pro action.js.erb, then everything works fine, see why it doesn’t work for you.

S
Sergey Krasnodemsky, 2014-12-16
@Prognosticator

Read for understanding.
And then see a similar question.

D
Danila Zaitsev, 2014-12-17
@Jukeboxx

index.html.erb

<%= form_tag ads_path, :method => 'get', :id => "ads_search" do %>
    	<%= label_tag("Поиск по тексту:") %>
    <%= text_field_tag :search, params[:search] %>
    <br/>
  <a class="btn btn-success"><%= submit_tag "Найти", :name => nil %></a>
<% end %>
<br/>
<div id="ads">
  <%= render 'ads' %>
</div>
<%= will_paginate @posts%>

index.js.coffee.erb
_ads.html.erb
<h1>Список объявлений</h1>

<table>
  <% @ads.each do |ad| %>
    <h2><%= link_to ad.title, ad %></h2>
    <%= ad.text %><br/>
    <strong>Город: </strong><%= ad.city.name %><br/>
    <strong>Дата публикации: </strong><%= ad.created_at %>
  <% end %>
</table>

ad.rb
class Ad < ActiveRecord::Base
  belongs_to :city
  attr_accessible :title, :text, :number, :published_date, :city_id
  
  def self.search(search)
    if search
      where('text LIKE ?', "%#{search}%")
    else
      Ad.all
    end
  end

end

ads_controller.rb
def index      
    @ads = @ads.paginate(:page => params[:page], :per_page => 50).order("created_at desc").search(params[:search])    
  end

application.js
//= require jquery
//= require jquery_ujs
//= require_tree .
$(function () {
      // Search form.
      $('#ads_search input').keyup(function () {
      $.get($('#ads_search').attr('action'), &crarr; 
        $('#ads_search').serialize(), null, 'script');
      return false;
      });
    });

It seems that all those files that were in the example indicated the volume.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question