Search with Ruby on Rails to generate a report

0

Well I have a project with scaffolds of books and loans and I need to do a search for a specific book and as a result show all the loans in that book had

I have no idea how to start doing this.

asked by anonymous 17.05.2018 / 20:58

1 answer

0

You can create a screen with a form where the user will enter the name of the book,  and, on the same screen, just below, display the search results (the book's loans searched). An example to follow would be:

First you need to have an association between the Book model and the Loan model.

In the model book add has_many

class Livro < ApplicationRecord
  has_many :emprestimos
end

And in the Loans model, add belongs_to

class Emprestimo < ApplicationRecord
  belongs_to :livro
end

Note: You must add the field libro_id in the table loans to the association to work

In the Loan controller, change the index method to:

def index
  if params[:search]
    # Aqui e realizada a pesquisa do livro através do nome que foi digitado, para saber mais pesquise sobre "sql Like"
    @livro = Livro.where("nome like ?", "%#{params[:search]}%").take

    # Aqui é verificado se algum livro foi encontrado para buscar os empréstimos deste livro "@livro.emprestimos"
    @emprestimos = @livro ? @livro.emprestimos : []
  else
    # Quando nada foi pesquisado, todos os empréstimos serão exibidos
    @emprestimos = Emprestimo.all
  end    
end

And use the loans / index.html.erb view to add the search form at the top of the page:

<%= form_tag(emprestimos_path, method: :get) do %>
  <%= text_field_tag 'search', nil, placeholder: 'Digite o nome do livro...' %>
  <%= submit_tag 'Pesquisar' %>
<% end %>

There are several ways to do this search, just a simple example to get an idea how to get started.

The examples I used are based on the videos in this channel: link

Creating a Search Form link

Associations link

    
21.05.2018 / 02:34