0

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!

1 Answer 1

1

Instead of using ajax to get JSON data, you could actually use ajax to get the entire rendered HTML and simply append the whole result into #spaces. First create a new action in your controller

Search Controller:

def result
  @spaces = Space.find_spaces(params)
end

route.rb

match "search/result" => "search#result"

Then your view views/search/result.html.erb

<% @spaces.each do |space| %>
<h1><%= space.name %></h1><p><%= space.description %></p>
<% end %>

now you can use ajax to get the rendered view from rails and put it whole using javascript

$( document ).ready(function() {
    $( "#search_form" ).submit(function() {
        $('#spaces').empty();
        $.get( "/search/result", $('#search_form').serialize())
        .done(function( search_result_html ) {
            $("#spaces").html( search_result_html );
        });
    }).trigger('submit'); //this is to submit on page load if coming from home page
});

That way you render everything at view/search/result.html.erb and use whatever rails helper you want

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, explained nicely. Nowhere in the docs does it really go into detail of the flow like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.