I need to make a simple API and add the following functionality:
GET /tools?tag=node (EXAMPLE)
The Tool model has the following columns:
* title (string)
* description (text)
* link (string)
* tags (array of strings)
I need to be able to search from localhost all the tools that have some tag in it. I try to use Rack Reducer but this method only works on string or text types.
I know this should be simple, but I'm new in Rails.
Thanks for any help.
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
pg_searchgem is pretty useful