Question

I've been following several railscasts and currently have a product list with endless page using will_paginate. I want to implement railscast #240 to add a live search into the results, but there seems to be some logical conflicts I'm not sure how to correct.

In simple terms, the endless page inside index.js.erb needs to add more products below the current list of products using append:

$('#products').append('<%= j render(@products) %>');

However the live search implementation needs to replace the current list of of products with new products from the search results:

$('#products').html('<%= j render(@products) %>');

Here's the full block:

    $('#products').html('<%= j render(@products) %>');  // live search
    $('#products').append('<%= j render(@products) %>'); // endless page
    <% if @products.next_page %>
        $('.pagination').replaceWith('<%= j will_paginate(@products) %>');
    <% else %>
        $('.pagination').remove();
    <% end %>

Both html() and append() work perfectly for their respective use, and if I comment one out the other works, but if I don't comment one out it gets really wonky.

How can I set it up so if the user is typing in the search box it triggers html() and if the user is scrolling it triggers append()? is there any way to determine which event triggered the index.js.erb call?

Was it helpful?

Solution

Figured it out in case it ever comes up for anyone else. Probably obvious to most experienced rails people but as a newbie it's a whole new concept for me.

I refactored the search results out into another controller and view, which let me use a seperate js.erb file to replace the content of #products while the products controller handles the scrolling endless-page.

So now I have views>products>index.js.erb using $('#products').append and views>results>index.js.erb for $('#products').html etc

I also had to create a results_controller.rb index action as well as a results resource to my route file.

After that both work simultaneously.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top