d34th4ck3r d34th4ck3r - 1 month ago 7
Ruby Question

how to make an asynchronous call to model and controller and get its values in views?

I'm trying to make a instant search like application in Ruby On Rails and Backbone.js .

I have stored all the words in a Model named

Dictionary
. It contains list of all the words.
Now, I want to make a search bar, where if I type "c" , I want list all the words starting with "c" similarly, if I type "ca" , It should list all the words starting with "ca".

Is there a Open Source application , from where I can learn ?

Answer

I have not tested this code. There might be typos, but I think it would work. Please comment so I can edit if it doesn't work

view

<%= text_field_tag 'search', :nil, :class => "search_box" %>
 <ul class="results">
    <span class="spinning" style="display:none;"></span>
 </ul>

jquery

$(".search_box").keyup(function(){
    $.get ("/search/" + this.value)
    $(".spinning").show()
)}

routes.rb

get "/search/:search" => "dictionaries#search", :as => :search

dictionaries_controller.rb

def search
 @dictionarys = Dictionary.where("word LIKE ?", params[:search])
end

views/dictionarys/search.js.erb

$(".results").empty().append("<%= j( render @dictionaries) %>"
$(".spinning").hide()

views/dictionarys/_dictionary.html.erb partial

<li><%=dictionary.word%></li>
Comments