user3110815 user3110815 - 4 months ago 6
Ruby Question

Duplicate Results From Search Params

I have a search method and two models, restaurants and menus.In the menu search method, if I search for "chicken" it shows the closest restaurants near the location that sells meals with word chicken example "chicken sandwich" with the use of association. The problem is, if a restaurant sells multiple chicken meals the restaurant is rendered several times.I want to be able to show restaurants once and when the button is clicked a modal shows the meals with "chicken" in the name using a loop if there are multiple meals with chicken. I tried adding uniq & uniq(&:restaurant_id) in the ActiveRecord and also controller & also trying "DISTINCT" using sql but nothing.

Example of problem

Controller

def search_for_menus
#@restaurant= Menu.restaurant.all
@menus = Menu.search_for_menus(params)
end


Menus Model

belongs_to :restaurant
reverse_geocoded_by "restaurants.latitude", "restaurants.longitude"

def self.search_for_menus(params)

menus=Menu.where("dish LIKE ?", "%#{params[:dish]}%") if params[:dish].present?
menus = menus.where("menus.price <=?",params[:max ])
menus = menus.where("menus.price >=?",params[:min ])

menus= menus.joins(:restaurant).near(params[:location],2)

menus
end
end


Search Page HTML

<% if @menus.present? %>
<%@menus.each do |menu| %>
<br>
<br>


<div id ="restaurants">
<div class="box">
<div class="thumbnail box-image">

<%= link_to (image_tag (menu.restaurant.thumbnail.url(:medium))),restaurant_path(menu.restaurant),'data-no-turbolink' => true%>

<div class="caption">
<h3 class="text-center"><%=menu.restaurant.name%></h3>

<p class="text-center"><a href="#" class="btn btn-primary text-center" role="button" data-toggle="modal" data-target="#modal-<%= menu.id %>">View Food</a></p>
</div>
</div>

</div>

<div id="modal-<%= menu.id %>" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="col-md-6">
<p><%= menu.dish %></p>
</div>
<div class="col-md-6">
<p><%= menu.price %></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>

</div>
</div>
</div>
</div>
</div>



<%end%>



</div>




<%else%>

<p>no posts</p>

<%end%>

Answer
belongs_to :restaurant
  reverse_geocoded_by "restaurants.latitude", "restaurants.longitude"

  def self.search_for_menus(params)

    menus=Menu.where("dish LIKE ?", "%#{params[:dish]}%") if params[:dish].present?
    menus = menus.where("menus.price <=?",params[:max ])
                 .where("menus.price >=?",params[:min ])
    menus.joins(:restaurant).near(params[:location],2).group(:id)
  end
end
Comments