PMP
PMP

Reputation: 231

Ruby TMDB API Save a Movie to database

I am using the ruby tmdb gem to find movies from TMDB. I have my API key set up and I know how to find a movie in the rails console

So Say I run this @movies = TmdbMovie.find(:title => 'The Social Network') in the rails console This returns a whole bunch of information about the aforementioned movie, The Social Network.

What I need to know, is how I can save the returned movie information to my database, and potentially create a new movie based on the returned information.

So say it run @movies = TmdbMovie.find(:title => 'The Social Network') and the console returns this View Gist on Github

What if i want to save, from that returned info, just the description, trailer and title to my database

Upvotes: 0

Views: 1001

Answers (2)

rails4sandeep
rails4sandeep

Reputation: 1867

I am not sure if you are legally allowed to save the tmdb data into your own database.You need to hit their api to get the movie info or cache it from time to time. You should not save it into your database.... The solution provided by kardeiz is the way to go....

Upvotes: 0

Jacob Brown
Jacob Brown

Reputation: 7561

Assuming you have a model set up to contain this data, you could do:

@movies.each do |movie|
  # assumes @movies is an array
  # inside this loop, "movie" refers to the current TMDB movie object
  YourMovie.where({
    description: movie.description,
    trailer: movie.trailer,
    title: movie.title
  }).first_or_create
end

YourMovie is just a reference to whatever you want to call your movie model; in your case (with a DB table called movies) it would be Movie.

If you don't already have an ActiveRecord model set up, you can generate one easily: rails g model YourMovie description trailer movie.

If you don't really need to store the movie in your local database, and just want to prevent hitting the API service constantly, you could use Rails low-level caching:

Rails.cache.fetch('The Social Network', expires_in: 24.hours) do
  @movies = TmdbMovie.find(:title => 'The Social Network')
end

Upvotes: 0

Related Questions