I have a search page on a rails app. The Search controller fetches the spaces based on a query in the model, and returns them as json. I'm using $.getJSON in a view to fetch them:
Search Controller:
respond_to :html, :js
def index
@spaces = Space.find_spaces(params)
end
Space model
def self.find_spaces(params = {})
params ||= {}
spaces = Space.all
spaces = spaces.near(params[:location], 10) if params[:location].present?
# spaces = space.where("name LIKE ? ", params[:name]) if params[:name].present?
spaces = spaces.where("description LIKE %?%" , params[:description]) if params[:description].present?
spaces
end
Script (views/search/index.html.erb)
$( document ).ready(function() {
$( "#search_form" ).submit(function() {
// clear out current results first
$('#spaces').empty();
// fetch all results
$.getJSON( "/search.json", $('#search_form').serialize())
.done(function( data ) {
$.each(data, function(key, space) {
$('#spaces').append("<h1>" + space.name + "</h1><p>" + space.description + "</p>");
});
});
}).trigger('submit'); //this is to submit on page load if coming from home page
});
This is all working fine, and I can access the JSON object, and display it in the view using jquery, and it all updates without refresh as expected, with the right results based on the form/query.
My question is regarding working with the Json data in the view.
Am I doing this right? Seems a bit silly, as now I can't use any Rails helpers (for instance link helpers) in my view, as it's just javascript/json object. I don't want to end up appending a horrible mess of html with object ids etc to create links.
Is there a proper/better way I should be doing this? I've read through the docs and a few other tutorials, but nowhere really (at all) describes the best way of working with returned Json in a view. Should I be using partials? .js.erb files? Magic?
Thanks for any enlightenment!