I have 2 tables, one called movies and one called users. User can add a movie to their watchlist. When a user does so the app creates a new record in my movies table with the movie name, id, release date etc. So it's possible to have 3 records of the same movie. But all with different user id's. This is not preferable.
So I'm trying to figure out how to check if a record (movie with a movie_id
value) already exists. If the movie already exists, to add the current users id to the user id
colum so that multiple users can share the same movie record. If it does not exist yet, create a new record.
This is my current create function in my movies.rb controller,
def create
respond_with Movie.create(movie_params.merge(user_id: current_user.id))
end
And in my movies model I have,
belongs_to :user
And I'm using Angular as my front-end framework, so this is my angular addMovie function,
movieAdd.add()
.then(function(response){
$scope.movieListID = response;
console.log ('Not empty' + $scope.movieListID)
for (var i = 0; i < $scope.movieListID.releases.countries.length; i++) {
var release = $scope.movieListID.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
if(typeof releaseNL === 'undefined'){
// With release date
Notification($scope.movieListID.original_title + ' is toegevoegd, maar heeft nog geen Nederlandse premiere datum.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
} else {
Notification.success($scope.movieListID.original_title + ' is toegevoegd.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: releaseNL.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
};
})