How to make a search field with form_tag in Rails?

Asked

Viewed 720 times

1

Hello! Good afternoon, sir. I am a student of information systems and I am doing a small project where I need to place a form to search for the objects of the model Product that exist in the database.

the product model:

class Produto < ApplicationRecord
  belongs_to :fornecedor

  def self.search(search)
    if search
      find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    else
      find(:all)
    end
  end

end

Controller products:

class ProdutosController < ApplicationController
  attr_accessor :nome
  before_action :set_produto, only: [:show, :edit, :update, :destroy]

  # GET /produtos
  # GET /produtos.json
  def index
    @produtos = Produto.all
  end

  def show
  end

  def getbusca
    @produts = Produto.search(params[:search])
  end

  def new
    @produto = Produto.new
  end

  def edit
  end

  def create
    @produto = Produto.new(produto_params)
    respond_to do |format|
      if @produto.save
        format.html { redirect_to @produto, notice: 'Produto was successfully created.' }
        format.json { render :show, status: :created, location: @produto }
      else
        format.html { render :new }
        format.json { render json: @produto.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @produto.update(produto_params)
        format.html { redirect_to @produto, notice: 'Produto was successfully updated.' }
        format.json { render :show, status: :ok, location: @produto }
      else
        format.html { render :edit }
        format.json { render json: @produto.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @produto.destroy
    respond_to do |format|
      format.html { redirect_to produtos_url, notice: 'Produto was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_produto
      @produto = Produto.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def produto_params
      params.require(:produto).permit(:nome, :preco, :fornecedor_id)
    end
end

A view start.html.erb from the Home Library:

<%= form_tag produtos_path, :action => 'getbusca', :method => 'get' do %>
      <p>
        <%= text_field_tag :search, params[:search] %>
        <%= submit_tag "Search", :name => nil %>
      </p>
  <% end %>

Routes:

Rails.application.routes.draw do

  root 'login#new'
  get '/home/inicio', to: 'home#index'
  get '/produtos', to: 'produtos#getbusca'

  scope '/login' do
    post '/', to: 'login#criarusuario'
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end

the mistake:

Couldn’t find all Products with 'id': (all, {:conditions=>["name LIKE ?" , "%arroz%"]}) (found 0 Results, but was Looking for 2)

on the line:

  def self.search(search)
    if search
      **find(:all, :conditions => ['name LIKE ?', "%#{search}%"])**
    else
      find(:all)
    end

1 answer

1


Hello, in your form you are putting produtos_path which refers to the Productoscontroller#index of your application.

So that you your action getbusca you need to create this route and add it to your form.

Or an approach that I consider better would be to put your search in the same Index, replacing

  def index
    @produtos = Produto.all
  end

for

  def index
    @produtos = Produto.search(params[:search])
  end

I think I would already.

EDIT:

This error you presented is generated because the method find since Rails 4 has been deprecated, so you should use where in place, follows example:

 def self.search(search)
    if search
      where(['name LIKE ?', "%#{search}%"])
    else
      all
    end
 end
  • Hello ! So, I already solved this route problem and the form is redirecting to the method search of Product. but I’m having an error. I updated the question with him

  • Try now @Mikhaelaraujo

  • It worked! Thank you ^ ^'

  • Oops, you’re welcome. Thanks for the upvote :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.