views:

48

answers:

2

This is working as is, but I'm pretty sure this is sloppy. Any tips on how to get all of this logic more rails-ish? I'm trying to implement will_paginate with this, but first I need a cleaner way of selecting the right records.

#shoe table
-------------------------------------
size  | brand     | color   | sold
-------------------------------------
8       somebrand   black     false
10      another     brown     true
-------------------------------------


def index

  @shoes = Shoe.find_all_by_sold(false, :include => :assets)

  #params[:size] = '8,9,10,11,11.5' || '8,9' || 'all'
  if params[:size]
    sizes = params[:size].split(',')
    @shoes.reject! { |shoe| !sizes.include?(shoe.size.to_s) } unless sizes.include?('all')
  end

  # params[:color] = 'brown,black' || 'brown' || 'all'
  if params[:color]
    colors = params[:color].split(',')
    @shoes.reject! { |shoe| !colors.include?(shoe.color.parameterize) }  unless colors.include?('all')
  end

  # params[:brand] same as the others
  if params[:brand]
    brands = params[:brand].split(',')
    @shoes.reject! { |shoe| !brands.include?(shoe.brand.parameterize) } unless brands.include?('all')
  end

end
+2  A: 

You could create some named scopes such as by_size, by_colour and by_brand on your Shoe model for these queries. Then you can chain them together in various permutations.

This Railscast should give you the idea.

John Topley
+3  A: 

You are most definitely reinventing the wheel here.

Step 1: Read up on named scopes.

Step 2: Look at searchlogic

jdl