SQL Query to Rails 3 for average user ratings -


i have rails app rates restaurants on specific dimensions using letsrate gem. i'd calculate average of ratings each restaurant , display user in array on index page.

my sql query -

select avg(stars) restaurants r, rates rs rs.rateable_id = r.id group r.name;  

the array in index looks -

<% @restaurants.each |restaurant| %> <li>     <a href="<%=restaurant_path(restaurant) %>" >         <div class="left">             <h2 class="name"><%= restaurant.name %></h2>             <h3 class="location"><%= restaurant.location %></h3>         </div>         <div class="right">             <h4 class="rate">average rating</h4>         </div>         <div class="clear"></div>     </a> </li> <% end %> 

wondering how translate sql query rails display averages in array.

if setup relations correctly, should work. if not i'll fix them.

edit

in restaurant controller:

class restaurantcontroller > applicationcontroller    def index     @restaurants = rate.joins(:restaurant).select("avg(rates.stars) res_avg, restaurants.name, restaurant.location").group("restaurants.name")   end end 

in restaurant index.html.erb:

<% @restaurants.each |restaurant| %> <li>   <a href="<%=restaurant_path(restaurant.id) %>" >     <div class="left">         <h2 class="name"><%= restaurant.name %></h2>         <h3 class="location"><%= restaurant.location %></h3>     </div>     <div class="right">         <h4 class="rate"><%= restaurant.res_avg %></h4>     </div>     <div class="clear"></div>   </a> </li> <% end %> 

edit2 if want re-use query declare in scope on model.

class restaurant < activerecord::base   #all model code   scope :avg_restaurant_rates, joins(:rate).select("avg(rates.stars) res_avg, restaurants.name, restaurants.location").group("restaurants.name") end 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -