Ruby on Rails search to generate a report

Asked

Viewed 315 times

0

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

I have no idea how to start doing that.

NOTE: I’m starting a little while with ruby on Rails and I need it a lot, I’ve seen many articles on the internet but they didn’t help me much.

Good Andersson Brantes, the code that you put in the logic that I needed, the video lessons too, only that I can not fit this research in my index that is so

def index
 @emprestimos = emprestimo.all.page(params[:page]).per(20)
 respond_to do |format|
   format.js { render json: @emprestimos, status: 200 }
   format.html
   format.json
   format.pdf {render template: 'emprestimos/report', pdf: 'report'}
 end

end

1 answer

0

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

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

In the Book model add has_many

class Livro < ApplicationRecord
  has_many :emprestimos
end

And in the Emprestimos model add belongs_to

class Emprestimo < ApplicationRecord
  belongs_to :livro
end

Note: You need to add the free field

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 emprestimos/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, it’s just a simple example to get an idea of how to start.

The examples I used are based on the videos on this channel: https://www.youtube.com/watch?v=ZHPondVB9RQ&list=PLe3LRfCs4go-mkvHRMSXEOG-HDbzesyaP

Creating a Search Form https://www.youtube.com/watch?v=WYcdrBAkR8s

Associations https://www.youtube.com/watch?v=vh3ir1XWfW0

Browser other questions tagged

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