I have an API in which i have a HABTM relationship between Characters and Movies (a movie has many characters and a character has many movies). I'm trying to set up a filter with has_scope gem so i can do something like /api/characters?by_movie=:movie_id
so instead of getting all the Characters from index in my CharactersController, i only get the characters that take part in a specific movie. The way the relationship is set up allows me to do something like Characters.find(1).movies
-> returns the list of movies of that character. And if i send a POST to character and i want to add movies to it i can do it like "movie_ids":[1,2].
I have tried this approach with no success:
in my Character.rb scope:by_movie, -> id, {where(movie_ids: id)}
and scope:by_movie, -> id, {where(movies: id)}
and in my controller: has_scope:by_movie, using: :id
The documentation in has_scope is very little, i wasn't able to find my specific problem, i hope some of you can help me, thank you.
Well, i figured it ou (sort of)
app/models/movie.rb
has_and_belongs_to_many :genres
scope :by_genre, -> (genres) {
genre_array = genres.split(',') # this turns the genre string into an array
joins(:genres).where(genres: genre_array) # this joins the genres table to our movies model, these tables are related already by a HABTM relationship.
}
And in our app/controllers/movies_controller.rb
has_scope :by_genre
@movies = apply_scopes(Movie).all
The only problem i can't solve is that if i pass let's say
localhost:3000/studios/movies?by_genre=1,2,3 #This is what your GET should look like. 1, 2 and 3 are the id's of the Genres the movie has.
say a movie has all three genres, so when i send this, i get as a result that one movie three times, and not only one result. So instead of comparing our genres_array with genre_ids array, it's sort of comparing each element of genres_array with genre_ids, one at a time. I haven't been able to solve this problem yet.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.