mruis
mruis

Reputation: 125

Rails search form, two models

I am trying to implement a search field in Rails 4 to find data behind two models. I have two controllers: buildings and rooms, and two models: building and room. A building, naturally, has many rooms and a room belongs to a building, which I have stated in the respective models.

Basically, a user could type either a building or a room name into the search form and it would return a response with details about the building or room. Of course, a building needs to have an address, and a room needs to know in which building it is with the address as well. So I'd need to display different details according to the searched for instance. Both have the same String attribute name, so this could make things easier.

I have no luck in finding a relevant example on how to implement such a search form. This is the working basic search I have at the moment in views\buildings\index.html.erb, which can only search buildings:

<%= form_tag({controller: "buildings", action: "show"}, method: "get", class: "nifty_form") do %>
  <%= label_tag(:name, "Search for a building (later also rooms):") %>
  <%= text_field_tag(:name) %>
  <%= submit_tag("Search") %>
<% end %>

This is the show method in controllers\buildings_controller.rb:

def show
  @building = Building.where('lower(name) = ?', params[:name].downcase).first
end

And this is the route it refers to:

get 'buildings/:id' => 'buildings#show'

Any and all help is appreciated!

Upvotes: 2

Views: 819

Answers (2)

mruis
mruis

Reputation: 125

Due to time restrictions, I decided to merge these models into one common model, Space. It holds all the information that a building and a room needs. Thanks anyways!

Upvotes: 0

luster
luster

Reputation: 148

I would recommend you to add the search code in the index method of buildings controller, there are many things you can do but here is what i will recommend:

def index
   # 
   if params.has_key?(:name)
     @buildings = Building.joins(:rooms).
                  where([
                     'lower(buildings.name) like ? or lower(rooms.name) like ?', 
                     "%#{params[:name].downcase}%",
                     "%#{params[:name].downcase}%"
                  ])
   else
     # your normal code goes here.
   end
end

Any other information you need such address ( is that a different model ) can he included in there.

Hope this helps,

PD: if necessary you can render a different view when a search is present inside your if block

render action: 'my_custom_view', status: :ok

Upvotes: 2

Related Questions