使用JSONAPI资源按连接表的字段进行筛选

时间:2017-07-07 15:53:59

标签: ruby-on-rails activerecord jsonapi-resources

我有三张桌子:

  1. 观察
  2. 子类别
  3. 分类
  4. 具有以下结构:

    class Observation < ApplicationRecord
      translates :name
      belongs_to :subcategory
    end
    
    class Subcategory < ApplicationRecord
      belongs_to :category
      has_many :observations
    end
    
    class Category < ApplicationRecord
      has_many :subcategories
    end
    

    我希望能够根据JSONAPI::Resource

    过滤category_id观察结果
    class ObservationResource < JSONAPI::Resource
      attributes :name, :subcategory_id
      filter :subcategory_id, :test
    
      filter :test, apply: ->(records, value, _options) {
        records.where('subcategories.category_id = ?', value[0])
      }
    end
    

    如果我尝试执行请求:

    /observations?include=subcategory,subcategory.category&filter[subcategory.category_id]=1
    

    我明白了:

      

    不允许使用subcategory.category_id

    如果我尝试执行请求:

    /observations?include=subcategory,subcategory.category&filter[test]=1
    

    在尝试执行时,我从Postgres得到一个例外:

      

    SQL(6.4ms)SELECT DISTINCT“观察”。“id”,“观察”。“id”   AS alias_0 FROM“观察”LEFT OUTER JOIN   “observation_translations”ON   “observation_translations”。“observation_id”=“观察”。“id”   WHERE(subcategories.category_id ='1')按“观察”排序。“id”   ASC限制$ 1 OFFSET $ 2 [[“LIMIT”,1000],[“OFFSET”,0]]

    因为表subcategories

    上没有联接

    如果我添加默认范围以包含subcategories所有查询都运行良好但最后一个查询失败,则在尝试计算记录时:

    SELECT COUNT(*) FROM "observations" WHERE (subcategories.category_id = '1')
    

    我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:0)

好的,解决方案是使用'join`:

filter :test, apply: ->(records, value, _options) {
  records.joins(:subcategory).where('subcategories.category_id = ?', value[0])
}