Advertisement
saasbook

scopes_example.rb

Aug 15th, 2013
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.02 KB | None | 0 0
  1. # BETTER: move filter logic into Movie class using composable scopes
  2. class Movie < ActiveRecord::Base
  3.   scope :with_good_reviews, lambda { |threshold|
  4.     Movie.joins(:reviews).group(:movie_id).
  5.       having(['AVG(reviews.potatoes) > ?', threshold])
  6.   }
  7.   scope :for_kids, lambda {
  8.     Movie.where('rating in ?', %w(G PG))
  9.   }
  10. end
  11. # in the controller, a single method can now dispatch:
  12. class MoviesController < ApplicationController
  13.   def movies_with_filters
  14.     @movies = Movie.with_good_reviews(params[:threshold])
  15.     @movies = @movies.for_kids          if params[:for_kids]
  16.     @movies = @movies.with_many_fans    if params[:with_many_fans]
  17.     @movies = @movies.recently_reviewed if params[:recently_reviewed]
  18.   end
  19.   # or even DRYer:
  20.   def movies_with_filters_2
  21.     @movies = Movie.with_good_reviews(params[:threshold])
  22.     %w(for_kids with_many_fans recently_reviewed).each do |filter|
  23.       @movies = @movies.send(filter) if params[filter]
  24.     end
  25.   end
  26. end
  27. # in the view:
  28. - @movies.each do |movie|
  29.   -# ...code to display the movie here...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement