[英]Using has_scope to filter by nested attributes in a HABTM relationship
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).我有一个 API,其中我有角色和电影之间的 HABTM 关系(一部电影有很多角色,一个角色有很多电影)。 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.我正在尝试使用 has_scope gem 设置过滤器,以便我可以执行类似/api/characters?by_movie=:movie_id
这样的操作,而不是从我的 CharactersController 中的索引中获取所有字符,我只获取参与的字符具体电影。 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.建立关系的方式允许我执行Characters.find(1).movies
-> 返回该角色的电影列表之类的操作。 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].如果我向角色发送 POST 并且我想向其中添加电影,我可以像“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
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. has_scope 中的文档很少,我无法找到我的具体问题,希望你们中的一些人能帮助我,谢谢。
Well, i figured it ou (sort of)好吧,我想通了(有点)
app/models/movie.rb应用程序/模型/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在我们的 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.因此,不是将我们的genres_array 与genre_ids 数组进行比较,而是将genres_array 的每个元素与genre_ids 进行比较,一次一个。 I haven't been able to solve this problem yet.我还没能解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.