Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # BETTER: move filter logic into Movie class using composable scopes
- class Movie < ActiveRecord::Base
- scope :with_good_reviews, lambda { |threshold|
- Movie.joins(:reviews).group(:movie_id).
- having(['AVG(reviews.potatoes) > ?', threshold])
- }
- scope :for_kids, lambda {
- Movie.where('rating in ?', %w(G PG))
- }
- end
- # in the controller, a single method can now dispatch:
- class MoviesController < ApplicationController
- def movies_with_filters
- @movies = Movie.with_good_reviews(params[:threshold])
- @movies = @movies.for_kids if params[:for_kids]
- @movies = @movies.with_many_fans if params[:with_many_fans]
- @movies = @movies.recently_reviewed if params[:recently_reviewed]
- end
- # or even DRYer:
- def movies_with_filters_2
- @movies = Movie.with_good_reviews(params[:threshold])
- %w(for_kids with_many_fans recently_reviewed).each do |filter|
- @movies = @movies.send(filter) if params[filter]
- end
- end
- end
- # in the view:
- - @movies.each do |movie|
- -# ...code to display the movie here...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement