user10410465
user10410465

Reputation:

In Rails how do I change the params of a controller method using a search form tag?

I'm building a Rails app that interacts with an external search API. I have a class method with the search functionality which is accessed by my index method in my design controller. How can I make it so that my form search changes the params of my controller method and thus performs a search? My code is below. Would appreciate the help :)

Class method:

class Api
  include HTTParty
  base_uri "http://search.exampleapi.com"

  attr_accessor :name

  # Find a particular design, based on its name
  def find(name)
    self.class.get("/designs", query: { q: name }).parsed_response
  end
end 

Controller:

class DesignsController < ApplicationController
    def index
        @search = Api.new.find(params[:q])['results']
    end
end

Routes.rb

Rails.application.routes.draw do
    root 'designs#index'
    resources :designs
end

View:

<h1>Search</h1>

<%= form_tag(controller: "designs", action: "search", method: "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>

<h2>Search results:</h2>

<% @search.each do |design| %>  
<h3><%= design['name'] %></h3>
<h5><%= design['thumbnail_url'] %></h5>
<% end %>

Upvotes: 1

Views: 187

Answers (1)

widjajayd
widjajayd

Reputation: 6253

since you using index page you can do, designs_path will automatically route you to index controller

<%= form_tag(designs_path, method: :get) do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>

Upvotes: 1

Related Questions