开发者

Move this logic into the find method?

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.incl开发者_运维问答ude?(shoe.brand.parameterize) } unless brands.include?('all')
  end

end


You are most definitely reinventing the wheel here.

Step 1: Read up on named scopes.

Step 2: Look at searchlogic


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜