Rails ransackable_scopes 小结

torvaldsdb · 2017年05月09日 · 最后由 stargwq 回复于 2017年05月09日 · 1924 次阅读

ransack今天遇到传递两个参数的 scope,然后查询使用ransackable_scopes的时候,文档ransack中没有太多说明。 自己就捣弄了一会儿。抛砖引玉!

store 的一个实例

[3] pry(main)> Store
=> Store(id: integer, block_id: integer, district: jsonb)
[13] pry(main)> Store.first
  Store Load (2.9ms)  SELECT  "stores".* FROM "stores" ORDER BY "stores"."created_at" DESC LIMIT $1  [["LIMIT", 1]]
=> #<Store:0x00000007aa6430
 id: 4,
 district: {"1"=>{"id"=>"710000", "name"=>"台湾省"}}>

原来的scope如下:

scope :store_district, -> (district_level, district_id) {
  where("district->'#{district_level}'->>'id' = ?", district_id)
}

查询:

[5] pry(main)> Store.count
   (2.5ms)  SELECT COUNT(*) FROM "stores"
=> 4
[6] pry(main)> Store.store_district("1", "710000")
  Store Load (3.1ms)  SELECT "stores".* FROM "stores" WHERE (district->'1'->>'id' = '710000') ORDER BY "stores"."created_at" DESC
=> [#<Store:0x000000071b9ed0
  id: 4,
  district: {"1"=>{"id"=>"710000", "name"=>"台湾省"}}>]

在 model 中声明:

class << self
  # ransackable scope
  def ransackable_scopes(auth_obj = nil)
    %i(store_district)
  end
end

只是接口没有想到好的参数传递方式。后来就改写了 scope`

scope :store_district, -> (*params) {
  params_hash = params.to_h.deep_symbolize_keys
  district_level, district_id = params_hash[:level], params_hash[:id]
  where("district->'#{district_level}'->>'id' = ?", district_id)
}

api 接口: localhost:3000/district/stores?store_district[level]=1&store_district[id]=710000 方法展示

# GET district/stores?page[number]=1&store_district[level]=1&store_district[id]=710000
def search_store_by_district
  stores = Store.search(params).result
  render ***
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号