Adrian Halaburda
Adrian Halaburda

Reputation: 50

Rails search in two models

I am new to rails and I want to make searches, I used ransack but not successful. I have a textfield in the navbar to find my aplication like this

layouts/_navigation.html.erb

<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <div class="container">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <div class="header">
        <img src="logo.png" alt="logo" />
        <a class="navbar-brand" href="/">BLABLABLA</a>
      </div>
    </div>

 <div class="navbar-collapse collapse">
   <%= search_form_for @search do |f| %>
          <div class="navbar-form navbar-right" role="form">
            <div class="form-group">
                <%= f.search_field :nombre_cont, class: "form-control" %> 
            </div>
              <%= f.submit "Buscar" , class: "btn btn-success btn-primary" %>
            </div>
       <% end %> 
    </div> <!--/.navbar-collapse -->

  </div>

would search for any word entered in the fields of two models in my HomeController

db/schema.rb

ActiveRecord::Schema.define(:version => 20140324120403) do

  create_table "departamentos", :force => true do |t|
    t.string   "nombre"
    t.integer  "interno"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "funcionarios", :force => true do |t|
    t.string   "nombre"
    t.string   "apellido"
    t.string   "cargo"
    t.integer  "departamento_id"
    t.integer  "interno"
    t.string   "correo"
    t.date     "cumpleanio"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

end

this would be the SQL query I want

SELECT funcionarios.* 
FROM funcionarios 
INNER JOIN departamentos ON departamentos.id = funcionarios.departamento_id 
WHERE 
(funcionarios.nombre LIKE '%VALUE%' OR 
funcionarios.apellido LIKE '%VALUE%' OR 
departamentos.nombre LIKE '%VALUE%' OR
departamentos.interno LIKE '%VALUE%')

any idea how to search?

Upvotes: 1

Views: 233

Answers (1)

nronas
nronas

Reputation: 181

What about try the following:

Funcionario.joins(:departamentos).where("nombre like '%?%' OR apellido LIKE '%?%' OR departamentos.nombre LIKE '%?%' OR departamentos.interno LIKE '%?%'", VALUE, VALUE, VALUE, VALUE)

I hope that helps.

Upvotes: 1

Related Questions