【发布时间】:2019-12-02 22:30:16
【问题描述】:
我需要制作一个简单的 API 并添加以下功能:
GET /tools?tag=node (EXAMPLE)
工具模型具有以下列:
* 标题(字符串)
* 描述(文字)
* 链接(字符串)
* 标签(字符串数组)
我需要能够从 localhost 中搜索所有带有标签的工具。 我尝试使用Rack Reducer,但此方法仅适用于字符串或文本类型。
我知道这应该很简单,但我是 Rails 的新手。
感谢您的帮助。
schema.rb:
ActiveRecord::Schema.define(version: 2019_11_29_170156) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "tools", force: :cascade do |t|
t.string "title"
t.string "link"
t.text "description"
t.text "tags", default: [], array: true
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
tools_controller.rb
class ToolsController < ApplicationController
ToolReducer = Rack::Reducer.new(
Tool.all,
# ->(tags:) { select { |item| item[:tags].match(/#{tags}/i) } }
->(tags:) { where("tags @> ?", "%#{tags}%") }
)
def index
# @tools = Tool.where(query_params)
@tools = ToolReducer.apply(params)
# @tools = Tool.all
render json: @tools
end
def new
@tool = Tool.new
end
def show
@tool = Tool.find(params[:id])
render json: @tool
end
def create
@tool = Tool.new(tool_params)
if @tool.save
render json: @tool
redirect_to @tool
end
end
def destroy
@tool = Tool.find(params[:id])
@tool.destroy
end
private
def tool_params
params.require(:tool).permit(:title, :link, :description, :tags)
end
end
【问题讨论】:
-
如果你的数据库是 Postgres
pg_searchgem 非常有用
标签: ruby-on-rails postgresql api ruby-on-rails-5