Gem Rails 5 + ransack + PosgreSQL 怎么借用 ransack 搜索 array?

lehug · 2017年08月25日 · 最后由 dingfengju 回复于 2017年08月25日 · 1605 次阅读

问题如上,找到一个解决方案是在 rails4 下,用 postgres_ext 这个 gem,但是这个 gem 不支持 rails5。没有看到 ransack 支持这一块的信息, 我期望的效果是类似 in 的效果。请教各位有何种解决方案?

# db/migrate/20140207133952_create_books.rb
create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'

# app/models/book.rb
class Book < ApplicationRecord
end

# Usage
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

## Books for a single tag
Book.where("'fantasy' = ANY (tags)")

## Books for multiple tags
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")

lehug 关闭了讨论。 10月30日 10:14
需要 登录 后方可回复, 如果你还没有账号请 注册新账号