Reputation: 3844
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.
Upvotes: 1
Views: 117
Reputation: 459
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!
Upvotes: 0
Reputation: 1738
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
Upvotes: 1