Search code examples
ruby-on-rails-3searchrotten-tomatoes

Rails search bar when data is not stored in model. Using an external API


I'm trying to create a search bar which will display all the results on the same page when someone searches. I'm stuck because I don't know how to do this when the data itself is not stored in the model. I'm using the BadFruit rails gem to query Rotten Tomatoes movie listings.

def search(movie_title)
   bf = BadFruit.new("YOUR_API_KEY_HERE")
   bf.movies.search_by_name(movie_title)
 end

The #search method returns an array with search result in index 0. I'd like the search result to show up in the same view as the search bar. Any help would be greatly appreciated!


Solution

  • It should make no difference whether the data comes from your own database or an external API. The controller should not care at all. It just fetches data using whatever search parameters, and renders the data in a form the front end can use. That's what MVC design is all about, keeping those layers separate.

    It sounds like you want to turn the search into an AJAX request. The javascript on the page will call the search request, and get back either a snippet of HTML or a chunk of JSON from your controller's search method. It will then either replace part of the page with the HTML snippet, or update the page using the data in the JSON block.

    Using something like KnockoutJS can make updating the page with a JSON response even simpler and more straightforward.