【问题标题】:Using has_scope to filter by nested attributes in a HABTM relationship使用 has_scope 按 HABTM 关系中的嵌套属性进行过滤
【发布时间】:2021-04-19 23:57:17
【问题描述】:

我有一个 API,其中我在角色和电影之间建立了 HABTM 关系(一部电影有很多角色,一个角色有很多电影)。我正在尝试使用 has_scope gem 设置过滤器,以便我可以执行类似的操作 /api/characters?by_movie=:movie_id 所以我没有从我的 CharactersController 中的索引中获取所有角色,而是只获取参与特定电影的角色。 建立关系的方式允许我做类似Characters.find(1).movies -> 返回该角色的电影列表。如果我向角色发送 POST 并且我想向其中添加电影,我可以像 "movie_ids":[1,2] 那样做。

我试过这种方法没有成功:

在我的 Character.rb scope :by_movie, -> id, {where(movie_ids: id)}scope :by_movie, -> id, {where(movies: id)} 以及我的控制器中:has_scope :by_movie, using: :id

has_scope 中的文档很少,我没能找到我的具体问题,希望你们能帮助我,谢谢。

【问题讨论】:

    标签: ruby-on-rails api has-scope


    【解决方案1】:

    嗯,我想通了(有点)

    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.
    }
    

    在我们的 app/controllers/movies_controller.rb 中

    has_scope :by_genre
    
    @movies = apply_scopes(Movie).all
    

    我唯一不能解决的问题是,如果我通过了让我们说

    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.
    

    假设一部电影具有所有三种类型,所以当我发送这个时,我会得到一部电影三遍的结果,而不仅仅是一个结果。因此,不是将我们的genres_array 与genre_ids 数组进行比较,而是将genres_array 的每个元素与genre_ids 进行比较,一次一个。我还没能解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多