1

I'm working on a social movie app in Rails. I do not wish to start from scratch on a database of movie info, so I've found a free and community-maintained movie database called The Movie Database (TMDB). It has a good API and documentation.

How would I design a Rails model that could be fully associated with my user model that can use a local record from my movies table, but if that record isn't there, make an API call to get the info?

I did a little research and it sounds like ActiveResource might do part of what I want, but it doesn't really offer associations with ActiveRecord.

Captain Stack
  • 3,572
  • 5
  • 31
  • 56

2 Answers2

1

I think it depends on how are you querying your local database to see if a movie is there and, if not, querying the api. Ideally, you should use the same ids from the api locally (maybe on a imdb_id field?) and query movies from there:

m = Movie.from_imdb_id(832903820)

where:

def self.from_imdb_id(imdb_id)
  m = Movie.where(imdb_id: imdb_id).first
  if m.blank?
    # I dont know how the api queries work so suggesting something here:
    data = RestClient.get("http://api.tmdb.com/movies/#{imdb_id}.json")
    m = Movie.create!(data.merge(imdb_id: imbd_id)
  end
  return m
end
Marcelo Ribeiro
  • 1,718
  • 1
  • 13
  • 27
  • This is pretty much what I came up with. I was mostly curious if there were other ways I should be considering, especially since I'm not too familiar with ActiveResource, which seems to pretty much do what I want except relate to ActiveRecord models. – Captain Stack Apr 25 '16 at 02:33
0

How about this:

Movie.find_or_create_by(imdb_id: imdb_id) do |movie|
  data = RestClient.get("http://api.tmdb.com/movies/#{imdb_id}.json")
  movie.director = data['director']
  .....
end

It would find a record corresponding to imdb_id, if not, would create a new one with the parameters in the block.

Regards!

Eason Caizhen Liu
  • 459
  • 1
  • 5
  • 12