Created
January 20, 2025 00:03
-
-
Save adamburvill/98226b0703f9b8ff7785547346d00a8a to your computer and use it in GitHub Desktop.
rights and genres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# RAILS METHOD | |
# RAILS QUERY 1: find the specific rights record based on the movie id and the rights _name_ | |
# under the hood sql query: SELECT * FROM rights WHERE movie.id = 5 AND rights.name = "CA" | |
# RAILS QUERY 2: update the specific rights record for the specific movie with the id we found in our first query | |
# under the hood sql query: UPDATE rights where id = 24 SET start = "" and end = "" | |
# SQL METHOD | |
# SQL QUERY 1: you don't have the id, use the name, try and find it, and then update if you find it in a single query | |
class RightsController < ApplicationController | |
def update_right | |
movie = Movie.find(params[:movie_id]) # Find the movie by ID | |
# Extract the rights data from the request | |
rights_data = params.require(:right).permit(:name, :start, :end) | |
# Find the right by name and movie | |
right = movie.rights.find_by(name: rights_data[:name]) | |
if right.nil? | |
render json: { error: "Right with name '#{rights_data[:name]}' not found for movie ID #{movie.id}" }, status: :not_found | |
return | |
end | |
# Update the fields (start and end) | |
if right.update(rights_data) | |
render json: { message: 'Right updated successfully', right: right }, status: :ok | |
else | |
render json: { errors: right.errors.full_messages }, status: :unprocessable_entity | |
end | |
end | |
end | |
class MoviesController < ApplicationController | |
def append_genres | |
movie = Movie.find(params[:id]) # Find the movie by ID | |
# Genres can be sent as an array of genre IDs or names | |
genre_ids = params[:genre_ids] # Example: [1, 2, 3] | |
genre_names = params[:genre_names] # Example: ['Action', 'Drama'] | |
if genre_ids.present? | |
# Append genres by IDs | |
genres = Genre.where(id: genre_ids) | |
movie.genres << genres | |
elsif genre_names.present? | |
# Append genres by names (create if they don't exist) | |
genres = genre_names.map { |name| Genre.find_or_create_by(name: name) } | |
movie.genres << genres | |
else | |
render json: { error: 'No genres provided' }, status: :unprocessable_entity | |
return | |
end | |
if movie.save | |
render json: { message: 'Genres successfully appended', movie: movie }, status: :ok | |
else | |
render json: { error: movie.errors.full_messages }, status: :unprocessable_entity | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment